如何在Swing java中的一行JTable中添加按钮
我做了一个摆动GUI,其中有JTable和一些行和列。我应该如何在JTable中的行中添加一个按钮?
我做了一个摆动GUI,其中有JTable和一些行和列。我应该如何在JTable中的行中添加一个按钮?
您可以将组件添加为表单元格。
首先,您应该实现一个类,该类具有作为其父类和两个接口:和。JButton
TableCellRenderer
TableCellEditor
它应该实现的原因是接收按钮的。TableCellEditor
ActionEvent
public class TableButton extends JButton implements TableCellRenderer, TableCellEditor {
private int selectedRow;
private int selectedColumn;
Vector<TableButtonListener> listener;
public TableButton(String text) {
super(text);
listener = new Vector<TableButtonListener>();
addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent e ) {
for(TableButtonListener l : listener) {
l.tableButtonClicked(selectedRow, selectedColumn);
}
}
});
}
public void addTableButtonListener( TableButtonListener l ) {
listener.add(l);
}
public void removeTableButtonListener( TableButtonListener l ) {
listener.remove(l);
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int col) {
return this;
}
@Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int col) {
selectedRow = row;
selectedColumn = col;
return this;
}
@Override
public void addCellEditorListener(CellEditorListener arg0) {
}
@Override
public void cancelCellEditing() {
}
@Override
public Object getCellEditorValue() {
return "";
}
@Override
public boolean isCellEditable(EventObject arg0) {
return true;
}
@Override
public void removeCellEditorListener(CellEditorListener arg0) {
}
@Override
public boolean shouldSelectCell(EventObject arg0) {
return true;
}
@Override
public boolean stopCellEditing() {
return true;
}
}
然后,我添加了一个 TableButtonListener' 来处理按钮事件,如下所示。EventListener named
public interface TableButtonListener extends EventListener {
public void tableButtonClicked( int row, int col );
}
并在渲染器/编辑器之上使用。
TableButton buttonEditor = new TableButton("Button");
buttonEditor.addButtonListener(new TableButtonListener() {
@Override
public void tableButtonClicked(int row, int col) {
// do something
}
});
TableColumn col = new TableColumn(1, 80);
col.setCellRenderer(buttonEditor);
col.setCellEditor(buttonEditor);
cols.addColumn(colPattern);
如果要为每行显示不同的按钮标签,则应在 和 方法中插入一个代码块来修改按钮的标签。getTableCellRendererComponent
getTableCellEditorComponent