Hello, I have made one swing GUI which have JTable with some rows and Columns.How should I add a button to row in a JTable ?
+1
A:
You don't add it to a row - you add it to the cell. This tutorial describes what you need
DroidIn.net
2009-09-25 05:34:45
ok,Thanks Droidln.net
om
2009-09-25 05:50:41
No need to thank, just tick the mark :)
DroidIn.net
2009-09-25 16:12:56
+3
A:
You can add Component as a table cell.
First of all, you should implement a class that have JButton as parent class and two interfaces that TableCellRenderer and TableCellEditor.
The reason that should implement TableCellEditor is for receiving button's ActionEvent.
public class TableButton extends JButton implements TableCellRenderer, TableCellEditor {
private int selectedRow;
private int selectedColumn;
public TableButton(String text) {
super(text);
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;
}
}
Then, I added a EventListener named TableButtonListener for handling button event as following.
public interface TableButtonListener extends EventListener {
public void tableButtonClicked( int row, int col );
}
And use above Renderer/Editor.
TableButton buttonEditor = new TableButton();
buttonEditor.addButtonListener(new TableButtonListener() {
@Override
public void tableButtonClicked(int row, int col) {
// do something
}
});
TableColumn col = new TableColumn(1, 80);
col.setCellRenderer(new TableButton());
col.setCellEditor(buttonEditor);
cols.addColumn(colPattern);
If you want to display different button's label for each row, you should insert code block into the getTableCellRendererComponent and getTableCellEditorComponent which is to modify button's label.
xrath
2009-09-25 05:50:38