I have been reading about the TableModelListener
(http://www.cs.auckland.ac.nz/compsci230s1c/lectures/xinfeng/swingmodelview.pdf) for a while now and I am trying to implement a Listener
for a JTable
which uses the AbstractTableModel
.
To explain the different parts of my program my class. My main class extends JFrame
and implements TableModelListener
so that is why I have this tableChanged method.
@Override
public void tableChanged(TableModelEvent e) {
if (e.getType() == TableModelEvent.UPDATE)
System.out.println("It is updated");
if (e.getType() == TableModelEvent.DELETE)
System.out.println("It is deleted");
}
My Class SwitchTableModel which extends AbstractTableModel
- Which is not the constructor - creates a table which displays some values which are taken from some other arrays. Part of the implementation is here Display the next row of a List in a JTable .
I use the constructor to call the SwitchTableModel class and create the JTable and the JFrame.
I have also added this row in to get when a value is updated.
public Object getValueAt(int rowIndex, int columnIndex) {
fireTableCellUpdated(rowIndex, columnIndex); ...
The thing that I would like to be able to edit my JTable
and then save its data, but although it seems that I could edit it, when I write smth for example in a empty field and press enter, it doesn't keep the data. The same happens when I try to change smth in a non-empty field.
Actually, with this code, it continues printing "It is edited" for the whole time that the JFrame stays open.
Any idea what I might be doing wrong?
***** EDIT ***** My constructor is like this:
final SwitchTableModel model = new SwitchTableModel(user_decide);
JTable table = new JTable(model);
JFrame frame = new JFrame ("Results");
table.getModel().addTableModelListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add (toolbar, BorderLayout.PAGE_START);
frame.getContentPane().add (
new JScrollPane(
table,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED),
BorderLayout.CENTER);
//frame.add(checkPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}