4

Brief description of a problem.

Assume we have JTable and user interacting with it in some way. TableModel of this table is constantly changing. How to ensure that when user tries to get some info from the table by referencing some constant column and currently selected row (by its rowIndex he got from JTable), he will not get into situation when TableModel is changed and his rowIndex obtained from JTable is no longer corresponding to same value in TableModel.

Following is initial question which explains problem in more detail:

Consider following situation:

  1. There is JTable which shows user info about currently running requests in some system

  2. When new request enters system, new row is being added to the table

  3. user can interact with table by right-clicking on a row (single row selection model is used in table) and choosing option from the menu (like: abort, postpone, retry, etc.)

  4. there is separate class which implements ActionListener interface (listens to the table) and handles all user interactions

  5. When user does some action on the table this class checks currently selected row and assigns some values for user's action (basically it takes index of selected row and then calls tableModel.getValueAt(indexOfSelectedRow, someValuableDataColumnIndex))

Now consider scenario when system is under stress test and requests are being submitted constantly with big frequency. This, in my case, leads to a bug, when sometimes class which handles user's actions gets wrong info from table model (action was called on one row, but action is done for another, usually next one). I believe this happens because during some inits in action handling class table model is changed because of new request accepted.

Question is, how to fix this. I am thinking about two approaches:

  • use something like invokeAndWait() for initialization in my user actions' handling class (don't like this idea, because imo it will lead to other unpredictable bugs)

  • creating separate listener class which will listen to user selections in the table and store data from selected row as soon as it was selected separately from TableModel. This way actions handling class will take data not from table model which is being changed, but from selected row, which is constant during the described scenario. (not sure this idea will work)

Please, comment on my ideas, and suggest yours.

I am sorry for absence of any code here, but original code will take way too much space, and model example isn't something what can be done easily here.

9
  • After thinking a bit about my second idea I realized it will not work. It has same two steps: 1) get selected row index 2) get info from table model for a row with that index. Any new row appearing in table in between of those two steps will screw things up.
    – GrayR
    Mar 2, 2012 at 2:02
  • 3
    How many threads access the TableModel? If more than one, how do they synchronize access? See also this sscce and this Q&A.
    – trashgod
    Mar 2, 2012 at 5:19
  • @trashgod TableModel is accessed by only one thread. Also thanks for links, intresting info. Can't figure anything helpfull from it as for now, but surely will look into it more deeply.
    – GrayR
    Mar 2, 2012 at 5:30
  • You might use one of the methods cited to verify EDT-only access to the model. Are rows ever deleted?
    – trashgod
    Mar 2, 2012 at 5:34
  • 1
    sounds like there might be something wrong in your code: the row selection is kept on the same "real" row. That is if a row is inserted above, the absolute index will increase but still point to the same object as before.
    – kleopatra
    Mar 2, 2012 at 9:52

2 Answers 2

4

I don't think inserting rows in a table changes the selection, so as long as you are updating the TableModel on the EDT, the selected row is still same when the user shows the popup and chooses and action from the popup.

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class TestJTableInsert {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                final DefaultTableModel model = new DefaultTableModel(0, 1);
                new Timer(500, new ActionListener() {
                    private final Random random = new Random();
                    private int data = 1;

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        model.insertRow(random.nextInt(model.getRowCount() + 1),
                                new Object[] { data++ });
                    }
                }).start();

                final JTable table = new JTable(model);
                JPopupMenu popup = new JPopupMenu();
                popup.add(new AbstractAction("Which row is this?") {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        JOptionPane.showMessageDialog(table,
                                "This is row " + table.getValueAt(table.getSelectedRow(), 0));
                    }
                });
                table.setComponentPopupMenu(popup);
                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.getContentPane().add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}
1
  • darn, you beat me - because I had to proof being human (by reading an near-to undeciferable captcha :)
    – kleopatra
    Mar 2, 2012 at 10:23
3

model example isn't something what can be done easily here.

Here's a starter to demonstrate that the selection is kept constant (in the sense that it always points to the same "real" row:

final DefaultTableModel model = new DefaultTableModel(0, 1);
for (int i = 0; i < 50; i++) {
    model.addRow(new Object[] {i});
};

final JXTable table = new JXTable(model);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowSelectionInterval(25, 25);
Action l = new AbstractAction("random insert") {
    Random random = new Random();
    @Override
    public void actionPerformed(ActionEvent e) {
        int row = random.nextInt(model.getRowCount());
        model.insertRow(row, new Object[] {"inserted at: " + row});
        table.scrollRowToVisible(table.getSelectedRow());
    }

};
new Timer(100, l).start();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.