我有:
- a
JTable
,嵌入在 a 中JScrollPane
,包含项目列表 - a
JPanel
,嵌入在 aJDialog
中,显示与所选项目相关的信息
代码按预期工作(信息得到更新),除了每次更改选择时JTable
失去焦点和获得焦点。JDialog
所以我添加了一个table.requestFocusInWindow
但JTable
仍然失去焦点,尽管调用返回 true。
如何确保JDialog
更新但JTable
不会失去焦点?
ps:我的最终目标是能够使用箭头(向上/向下)浏览表格并在 JDialog 中查看信息更新 - 目前,我需要单击行来执行此操作。
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);
}
}