Reputation: 25106
I am trying to nest a JTable inside of another JTable's column (using a CellRenderer).
Example (erroneous) output:
Why does the following example not output a table within a table?
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
public class Test {
public static void main(String[] args) {
JTable table = new JTable(new CustomTableModel());
table.setDefaultRenderer(Person.class, new CustomRenderer());
JPanel panel = new JPanel();
panel.add(new JScrollPane(table));
JFrame frame = new JFrame();
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
}
@SuppressWarnings("serial")
class CustomTableModel extends AbstractTableModel {
@Override
public int getColumnCount() {
return 2;
}
@Override
public int getRowCount() {
return 1;
}
@Override
public Object getValueAt(int row, int col) {
if (col == 0) {
return new Person("Bob");
} else {
return "is awesome!";
}
}
}
@SuppressWarnings("serial")
class CustomRenderer extends JPanel implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int col) {
JTable t = new JTable(new CustomTableModel());
add(new JScrollPane(t));
return this;
}
}
class Person {
public String name = "";
public Person(String name) {
this.name = name;
}
}
Upvotes: 4
Views: 4421
Reputation: 347214
Don't add the sub table to a scroll pane. Instead, try adding the table to the center position of a JPanel with a BorderLayout, then add the tables header to the NORTH position
The main reason for this is the scroll pane will not be interactive and may hide data
Updated
I'm on phone, so it's hard to read the code :P
In your main table model, you need to override the getColumnClass method and make sure you are retuning Person.class for the required column (and the correct class types for the other columns to)
Upvotes: 4