Is it possible to have multiple objects inside one JTable
cell looking like this where I have two JLabels
in each cell on the first row?
The problem I am having in this example is that I can't add any listeners to any JLabels
(Icons
). My guess is that I need to change something else then the CellRenderer
?
public class JTableIcons extends JPanel {
private DefaultTableModel model;
private JTable table;
public JTableIcons() {
initModel();
initTable();
this.setLayout(new BorderLayout());
this.add(table, BorderLayout.CENTER);
}
class MyRenderer implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
JPanel panel = new JPanel();
if (row == 0) {
JLabel lblCol = new JLabel("Column:" + column);
Icon icon = UIManager.getIcon("OptionPane.errorIcon");
JLabel lblIcon = new JLabel();
lblIcon.setIcon(icon);
panel.add(lblIcon);
panel.add(lblCol);
} else {
JLabel lbl = new JLabel("(" + row + "," + column + ")");
panel.add(lbl);
}
panel.setOpaque(false);
return panel;
}
}
private void initTable() {
table = new JTable(model);
table.setDefaultRenderer(Object.class, new MyRenderer());
table.setShowGrid(true);
table.setGridColor(Color.gray);
table.setRowHeight(80);
}
private void initModel() {
String[] cols = { "", "", "" };
Object[][] rows = { { "", "", "" }, { "", "", "" }, { "", "", "" }, { "", "", "" } };
model = new DefaultTableModel(rows, cols);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JTableIcons());
f.setVisible(true);
f.setSize(new Dimension(500, 350));
f.setLocationRelativeTo(null);
}
});
}
}
Don't use two components, when one will do. The renderer in this example implements the
Icon
interface to leverage the flexible relative positioning of the text and icon. When necessary, add multiple components to a suitable lightweightContainer
, e.g.JPanel
.For interactivity, use a custom
TableCellEditor
. This example manages radio buttons in a panel.