- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在做一个必须通过键盘读取一些字符并解释它们的应用程序。
为了捕获键,我打开了一个 JDialog 并设置了一个 KeyEventDispatcher,这样我就可以在 dispatchKeyEvent 方法中捕获字符。在 JDialog 中有一个按钮可以删除 KeyEventDispatcher 并处理 JDialog。
它有两个问题:
- 第一次打开 JDialog 时,好像没有设置 KeyEventDispatcher
- 当我关闭并打开此 JDialog 时,KeyEventDispatchers 正在累积(第一次打开时,没有运行;第二次打开时,有一个在运行,第三次打开时,有 2 个在运行,...)
似乎 KeyEventDispatchers 是在 JDialog 关闭时设置而不是删除,而不是在 JDialog 打开时设置并在关闭时删除。
有人可以帮助我了解发生了什么以及我该如何解决它吗?
这是 JDialog 类的简化版本(只有键捕获部分):
public class SequenceDialog {
private JDialog dialog;
private JButton finishButton;
private DialogKeyEventDispatcher keyEventDispatcher;
public SequenceDialog() {
initializeDialog();
}
private void initializeDialog() {
dialog = new JDialog();
finishButton = new JButton("Finish");
finishButton.addActionListener(new FinishButtonListener());
dialog.setModalityType(ModalityType.APPLICATION_MODAL);
dialog.add(finishButton);
setKeyListener();
dialog.setVisible(true);
dialog.pack();
}
/** Adds the KeyEventDispacther */
private void setKeyListener() {
keyEventDispatcher = new DialogKeyEventDispatcher();
KeyboardFocusManager manager = KeyboardFocusManager
.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(keyEventDispatcher);
}
private class FinishButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//Removing the KeyEventDispacther
KeyboardFocusManager manager = KeyboardFocusManager
.getCurrentKeyboardFocusManager();
manager.removeKeyEventDispatcher(keyEventDispatcher);
dialog.dispose();
}
}
/** The KeyEventDispatcher to be executed */
private class DialogKeyEventDispatcher implements KeyEventDispatcher {
public boolean dispatchKeyEvent(KeyEvent e) {
if(e.getID() == KeyEvent.KEY_PRESSED) {
System.out.println(KeyEvent.getKeyText(e.getKeyCode()));
}
return false;
}
}
}
如果有其他捕获 key 的方法,我会很乐意看到它。到目前为止,我已经尝试过:
最佳答案
无法重现首先无法正常工作的情况。
可以重现堆叠:通过单击标题中的关闭图标关闭对话框时不会删除调度程序。在这种情况下,在主框架中键入的笔画会在对话框关闭后打印出来。
调度程序可以在 dispose 和 WindowListener 中(而不是在 finish 操作中)可靠地删除:
private void initializeDialog() {
dialog = new JDialog() {
@Override
public void dispose() {
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.removeKeyEventDispatcher(keyEventDispatcher);
LOG.info("disposed: " + manager);
super.dispose();
}
};
WindowListener l = new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.removeKeyEventDispatcher(keyEventDispatcher);
LOG.info("closing: " + manager);
}
};
dialog.addWindowListener(l);
关于java - 第一次打开 JDialog 时运行 KeyEventDispacther,然后将其删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8961113/
我正在做一个必须通过键盘读取一些字符并解释它们的应用程序。 为了捕获键,我打开了一个 JDialog 并设置了一个 KeyEventDispatcher,这样我就可以在 dispatchKeyEven
我是一名优秀的程序员,十分优秀!