我已经实现了带有单元格渲染器的自定义表格,以便我可以在表格中的每一行添加删除按钮
按钮编辑器.java
public class ButtonEditor extends DefaultCellEditor{
protected TableButton btn;
private String lbl;
private Boolean clicked;
public ButtonEditor(JTextField txt) {
super(txt);
btn= new TableButton();
btn.setOpaque(true);
//WHEN BUTTON IS CLICKED
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// fireEditingStopped();
JOptionPane.showMessageDialog(btn, lbl+" Clicked");
}
});
}
//OVERRIDE A COUPLE OF METHODS
@Override
public Component getTableCellEditorComponent(JTable table, Object obj,
boolean selected, int row, int col) {
//SET TEXT TO BUTTON,SET CLICKED TO TRUE,THEN RETURN THE BTN OBJECT
lbl=(obj==null) ? "":obj.toString();
btn.setText(lbl);
clicked=true;
return btn;
}
//IF BUTTON CELL VALUE CHNAGES,IF CLICKED THAT IS
@Override
public Object getCellEditorValue() {
if(clicked)
{
JOptionPane.showMessageDialog(btn, lbl+" Clicked");
}
//SET IT TO FALSE NOW THAT ITS CLICKED
clicked=false;
return new String(lbl);
}
@Override
public boolean stopCellEditing() {
//SET CLICKED TO FALSE FIRST
clicked=false;
return super.stopCellEditing();
}
@Override
protected void fireEditingStopped() {
// TODO Auto-generated method stub
super.fireEditingStopped();
}
}
ButtonRenderer.java
public class ButtonRenderer extends JButton implements TableCellRenderer
{
//CONSTRUCTOR
public ButtonRenderer() {
//SET BUTTON PROPERTIES
setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object obj,
boolean selected, boolean focused, int row, int col) {
//SET PASSED OBJECT AS BUTTON TEXT
setText((obj==null) ? "":obj.toString());
return this;
}
}
在 JPanel 构造函数内,我需要在 swing 中添加一行已添加的表格调色板。
public samplePanel(){
table.addRow(new Object[] {o.get(0), o.get(1), o.get(2), o.get(3), o.get(4), "DELETE"});
table.getColumn("Action").setCellRenderer(new ButtonRenderer());
table.getColumn("Action").setCellEditor(new ButtonEditor(new JTextField()));
}
按钮编辑器和渲染器的参考请单击此处。
我只是想获取单击删除按钮的行的数据,但我不知道该怎么做,因为我是渲染器和编辑器的新手。
JTable 有一个鼠标点击监听器。 还有一个“ListSelectionListener”,但这种方式要容易得多(对于简单的情况)
我就是这样做的:
jTable1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
rowClicked(e);
}
});