我创建了自己的WYSIWYG编辑器,它由一个设计窗口和一个工具调色板窗口组成.
设计窗口是JFrame,工具选项板是将FocusableWindowState设置为false的JDialog.
但是,通过将FocusableWindowState切换为false,我无法再在我的工具选项板窗口中编辑JTable中的单元格.将其更改为true允许我编辑单元格.
这是我的代码示例:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(0, 0, 1024, 768);
JDialog paletteWindow = new JDialog(frame, false);
paletteWindow.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
paletteWindow.setResizable(false);
paletteWindow.setFocusableWindowState(false);
paletteWindow.setBounds(1024, 0, 320, 768);
JTable grid = new JTable(new DefaultTableModel(new String[] {"Name", "Value"}, 5));
paletteWindow.getContentPane().add(new JScrollPane(grid));
frame.setVisible(true);
paletteWindow.setVisible(true);
即使FocusableWindowState设置为false,我如何仍然编辑单元格?
最佳答案 我找到了我的问题的答案,虽然它可能不符合每个人的需要.我已经使用KeyEventDispatcher将关键事件从聚焦框架分派到编辑单元格编辑器.这是我的代码示例:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(0, 0, 1024, 768);
JDialog paletteWindow = new JDialog(frame, false);
paletteWindow.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
paletteWindow.setResizable(false);
paletteWindow.setFocusableWindowState(false);
paletteWindow.setBounds(1024, 0, 320, 768);
JTable grid = new JTable(new DefaultTableModel(new String[] {"Name", "Value"}, 5)) {
private KeyEventDispatcher dispatcher;
@Override
public Component getEditorComponent() {
final Component c = super.getEditorComponent();
if (dispatcher == null) {
dispatcher = new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
e.setSource(c);
for (KeyListener keyListener : c.getKeyListeners()) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
keyListener.keyPressed(e);
} else if (e.getID() == KeyEvent.KEY_RELEASED) {
keyListener.keyReleased(e);
} else if (e.getID() == KeyEvent.KEY_TYPED) {
keyListener.keyTyped(e);
}
}
return false;
}
};
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
}
return c;
}
@Override
public void removeEditor() {
if (dispatcher != null) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(dispatcher);
dispatcher = null;
}
super.removeEditor();
}
};
paletteWindow.getContentPane().add(new JScrollPane(grid));
frame.setVisible(true);
paletteWindow.setVisible(true);