[英]Closing a JDialog by hitting the “enter” on keyboard
I want to close my JDialog by hitting the "enter" key on my keyboard. 我想通过敲击键盘上的“ enter”键来关闭JDialog。 how can I do that?
我怎样才能做到这一点? thank you!
谢谢! NOTE: I want to do this, without any button involved.
注意:我要执行此操作,而不涉及任何按钮。 THank you!
谢谢!
One way: 单程:
eg, 例如,
myDialog.getRootPane().setDefaultButton(exitButton);
Option two: 选项二:
eg, 例如,
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class DemoDialog {
public static void main(String[] args) {
JFrame frame = new JFrame("Frame");
frame.add(Box.createRigidArea(new Dimension(400, 300)));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
final JDialog dialog = new JDialog(frame, "Dialog", true);
// set binding
int condition = JPanel.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = ((JPanel) dialog.getContentPane()).getInputMap(condition);
ActionMap actionMap = ((JPanel) dialog.getContentPane()).getActionMap();
String enter = "enter";
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), enter);
actionMap.put(enter, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.add(Box.createRigidArea(new Dimension(200, 200)));
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
}
I would like to say first that 'Hovercraft Full Of Eels' solution is more elegant than this one and more closely in the spirit of the JDialog
and Swing
API. 首先,我想说的是“气垫船充满鳗鱼”解决方案比这个解决方案更优雅,并且更符合
JDialog
和Swing
API的精神。 However, to offer an alternative here is a basic example of using a KeyListener
on your JDialog
that will do as you need without adding a button; 但是,这里提供一个替代方法是一个在
JDialog
上使用KeyListener
的基本示例,该示例将根据需要执行而无需添加按钮。
public class Test {
public static void main(String[] args) {
JDialog jd = new JDialog();
// Add and define the KeyListener here!
jd.addKeyListener(new KeyListener(){
@Override
public void keyTyped(KeyEvent e) {
// Nothing
}
@Override
public void keyPressed(KeyEvent e) {
// Nothing
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
JDialog d = (JDialog)e.getSource();
d.dispose();
}
}
});
// End key listener code
jd.setVisible(true);
}
}
The important/relevant code is between the two main comments. 重要/相关代码位于两个主要注释之间。 This is a compilable example, so you can copy paste this into a new file and run it to view the effects.
这是一个可编译的示例,因此您可以将其复制粘贴到新文件中并运行它以查看效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.