I have:
- a
JTable, embedded in aJScrollPane, containing a list of items - a
JPanel, embedded in aJDialog, that displays information related to the selected item
The code works as expected (information gets updated), except that the JTable loses focus and the JDialog gets the focus every time the selection is changed. So I have added a table.requestFocusInWindow but the JTable still loses the focus, although the call returns true.
How can I make sure that the JDialog gets updated but that the JTable does not lose the focus?
ps: My end goal is to be able to browse the table with the arrows (up / down) and see the information update in the JDialog – at the moment, I need to click on the rows to do that.
EDIT
See below a SSCCE that replicates my issue (the content of the JDialog changes when selection is changed but the focus is lost).
public class TestTable extends JTable {
public static JFrame f = new JFrame();
public static JTextField text = new JTextField();
public static JDialog dialog;
public static void main(String[] args) {
f.setSize(300, 300);
f.setLocation(300, 300);
f.setResizable(false);
showPopup();
final JScrollPane jScrollPane = new JScrollPane();
jScrollPane.getViewport().add(new TestTable());
f.add(jScrollPane);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public TestTable() {
super();
setModel(new TestTableModel());
getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
int row = lsm.getAnchorSelectionIndex();
Object item = getModel().getValueAt(row, 0);
text.setText(item.toString());
dialog.setVisible(true);
TestTable.this.requestFocusInWindow(); //DOES NOT DO ANYTHING
}
});
setCellSelectionEnabled(false);
}
public class TestTableModel extends DefaultTableModel {
public TestTableModel() {
super(new String[]{"DATA"}, 3);
setValueAt(Double.valueOf(-0.1), 0, 0);
setValueAt(Double.valueOf(+0.1), 1, 0);
setValueAt(Double.valueOf(0), 2, 0);
}
}
private static void showPopup() {
dialog = new JDialog(f, "Title");
dialog.setContentPane(text);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
}
There must be something in your dialog that grabs the focus on the fly, because I have tried with a JLabel and it does not cause any problem. If you need to work around this, you can always call
toFront()on your JTable parent Frame. If it does not help your case, try to edit this SSCCE to reproduce your issue.See this code (comment the grabFocus on the label to convince yourself that there is something in your dialog that grabs the focus):