I am trying to add radio button group similar to http://www.java2s.com/Code/Java/Swing-Components/RadioButtonTableExample2.htm
In my form, I followed the the above tutorial but I am using AbstractTableModel
instead of DefaultTableModel
.
Here is my code, it does not show anything on column no errors:
StudentTableModel model = new StudentTableModel(studentList);
// JScrollPane scrollPane = new JScrollPane(table);
final JScrollPane scrollPane = new JScrollPane(
table,
JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Dimension d = table.getPreferredSize();
scrollPane.setPreferredSize(
new Dimension(d.width,table.getRowHeight()*rows));
// code for radio buttons
String[] answer = { "A", "B", "C" };
TableColumnModel columnModel = table.getColumnModel();
for (int tc = 7; tc < table.getColumnCount(); tc++)
{
columnModel.getColumn(tc).setCellRenderer(
new MainClass().new RadioButtonRenderer(answer));
columnModel.getColumn(tc).setCellEditor(
new MainClass().new RadioButtonEditor(new JCheckBox(), new MainClass().new RadioButtonPanel(
answer)));
}
table.setModel(model);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.getContentPane().add(navigation, BorderLayout.SOUTH);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Thanks in advance
The code is trying to set renderer and editor before setting the model. So there are no columns to set a renderer/editor on. The model must be set first, only then the columns will be created - just creating the model does not link it to the table, the table does not know beforehand how many columns it will have.
Probably you want something like
StudentTableModel model = new StudentTableModel(studentList);
table.setModel(model); // moved from below
// JScrollPane scrollPane = new JScrollPane(table);
...
The example you are following is doing so, actually it creates the table with the model as argument...
Hint: why new MainClass()
in new MainClass().new RadioButtonRenderer(...
and others? You really want a new MainClass? Declare these classes as static
and remove the new MainClass()