Search code examples
javaswingjtabletablecelleditor

Use components in table cell, not just strings


How is it possible, to use components as cell content too, not just string, boolean, and integer.

String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
String[] columnNames = {"name", "elem"};
Object[][] data = {
    {"button", new JButton("test")},
    {"select", new JComboBox(petStrings)}
};

JTable table = new JTable(data, columnNames);

Now I can't see the button, and the combobox in the table, only javax.swing.JComboBox...

Maybe I should extend JTable somehow, but I have no idea how.


Solution

  • Read the JTable tutorial. Understand that you're already using components of a sort inside JTable cells. When displayed the JTable is rendering a TableCellRenderer, an object that must return a Component that is displayed by each cell. When a cell is being edited, then the JTable will display a (usually) different object, a component produced by theTableCellEditor. Your job then is to change your table's renderor and or editor, depending on your need, the steps of which are too long to show simply in this answer. Again, the tutorials will show you the way.

    Note that no matter what route you take in your solution, the JTable's cell renderer will not be displaying any actual components, but rather will only be displaying renderings of a component, and that's a big difference. The cell editor however will show an actual component, but only when the cell is in the act of being edited.

    As a second aside, the table is used as a tabular presentation of data, and usually, the same type of data is displayed in each column, so you'd have to make a strong argument to convince me to have a single JTable column sometime display a JButton and at other times a JComboBox.

    For instance, to have one JTable column's editor show a combo box, you could set its default cell editor to use the combobox like so:

      String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
      JComboBox<String> petCombo = new JComboBox<>(petStrings);
      String[] columnNames = {"name", "elem"};
      Object[][] data = {
          {"Pet 1", null},
          {"Pet 2", null}
      };
    
      DefaultTableModel model = new DefaultTableModel(data, columnNames);
      JTable table = new JTable(model);
      table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(petCombo));