我有一个JTable,它有几行,每行有一个按钮。不知怎的,我相信按钮不可点击。
这是我的代码:
public class JTableJButton {
JFrame frame;
JPanel panel;
JButton button;
JTable table;
DefaultTableModel tableModel;
public JTableJButton(){
frame = new JFrame("Frame");
panel = new JPanel();
button = new JButton("Remove");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent arg0) {
System.out.println("Pressed");
}
});
String col[] = {"number", "name#", "button"};
tableModel = new DefaultTableModel(col, 0);
Object[] data1 = {"1", "name1", button};
tableModel.addRow(data1);
Object[] data2 = {"2", "name2", button};
tableModel.addRow(data2);
Object[] data3 = {"3", "name3", button};
tableModel.addRow(data3);
table = new JTable(tableModel){
@Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
TableCellRenderer buttonRenderer = new JTableButtonRenderer();
table.getColumn("button").setCellRenderer(buttonRenderer);
TableCellEditor editor = new myEditor();
table.getColumn("button").setCellEditor(editor);
panel.add(new JScrollPane(table));
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
// TODO code application logic here
new JTableJButton();
}
private static class JTableButtonRenderer implements TableCellRenderer {
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JButton button = (JButton)value;
return button;
}
}
那么是否有任何想法让按钮工作并使其执行删除所选行等功能?
编辑:根据广告中提供的链接,我注意到我需要创建一个CellEditor类,如下所示:
public class myEditor extends AbstractCellEditor
implements TableCellEditor,
ActionListener {
private Object editorValue;
@Override
public Object getCellEditorValue() {
return editorValue;
}
@Override
public Component getTableCellEditorComponent(JTable jtable, Object o, boolean bln, int i, int i1) {
}
@Override
public void actionPerformed(ActionEvent ae) {
System.out.print("HI");
}
}
但我仍然迷失了,我不明白这些方法使按钮工作的程序。我读了How to Use Tables: Using Other Editors,但仍然无法根据我的情况弄清楚方法中必须包含哪些数据。任何人都可以提供任何例子,只是为了让我知道它是如何工作的吗?