在下面的方法中,当我点击按钮helpBut时,将显示JTextArea。显示帮助文本(用JTextArea:helpText编写的文本)后,我想通过按下转义键关闭此文本。我试图使用addKeyListener方法(下图),但它没有用。
public void clickButton (JButton helpBut, JTextArea helpText)
{
helpBut.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JPopupMenu helpPopup = new JPopupMenu();
helpPopup.add(helpText);
if (!helpPopup.isVisible()) {
helpPopup.show(helpBut,20,20);
} else {
helpPopup.setVisible(false);
}
}
});
helpText.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(helpText.isVisible()) {
if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
helpText.setVisible(false);
}
}
});
}
我发现只有当我点击JtextArea时,编译器才会调用方法addKeyListener。
非常感谢,我使用像snow_1803的建议这样的键绑定,并且它有效。
helpPopup.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ESCAPE"), "closeJTextArea");
helpPopup.getActionMap().put("closeJTextArea", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
helpPopup.setVisible(false);
}
});