I probably do not understand how the method fireTableStructureChanged() works. I am assuming that if I call the method, the implemented methods getColumnCount(), getRows() and getValueAt(int row, int col) are called so that my Table with the specified Model changes.
This is my TableModel
public class MyTableModel extends AbstractTableModel{
JComboBox box;
public MyTableModel(JComboBox choice){
super();
box = choice;
}
public void updateTable(){
this.fireTableStructureChanged();
}
@Override
public int getColumnCount() {
//implemented
}
@Override
public int getRowCount() {
//implemented
}
@Override
public Object getValueAt(int row, int col) {
//implemented
}
choice5 is a JComboBox
table1 = new JTable(new MyTableModel(choice5));
When you select an item from choice5
((MyTableModel)table1.getModel()).updateTable();
is called (edit: for every item i can selected i probably have a diferent jtable i want to display)
What happens: I've checked that getColumnCount() and getRowCount() are indeed called, but getValueAt(...) is not. The JTable table1 (which was not displayed due to 0 rows and 0 columns) is still not displayed though both methods return (i.e.) the value 1.
What I want to happen: Obviously, I want table1 to be displayed (i.e. with one column and one row) with correct values (returned by getValueAt(...)).
Why is the method getValueAt(...) not called and therefore (I belive) the table not displayed? In general, how does fireTableStructureChanged() work?
Thanks in advance.
edit(SSCCE):
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTable;
public class TestTableModel extends JFrame {
static JComboBox<String> choice5 = new JComboBox<String>(new String[]{"","1","2","3"});
static JTable table1 = new JTable(new MyTableModel(choice5));
static JFrame frame = new JFrame();
public static void main(String[] args) {
frame.setLayout(new BorderLayout());
choice5.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
((MyTableModel)table1.getModel()).updateTable();
frame.pack();
}}});
frame.add(BorderLayout.SOUTH, choice5);
frame.add(BorderLayout.CENTER, table1);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
MyTableModel
import javax.swing.JComboBox;
import javax.swing.table.AbstractTableModel;
public class MyTableModel extends AbstractTableModel{
JComboBox box;
public MyTableModel(JComboBox choice){
super();
box = choice;
}
public void updateTable(){this.fireTableStructureChanged();}
@Override
public int getColumnCount() {return box.getSelectedIndex();}
@Override
public int getRowCount() { return box.getSelectedIndex();}
@Override
public Object getValueAt(int row, int col) {return box.getSelectedItem();}
}