Reputation: 111
I want to close my JDialog by hitting the "enter" key on my keyboard. how can I do that? thank you! NOTE: I want to do this, without any button involved. THank you!
Upvotes: 0
Views: 2408
Reputation: 12962
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. 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;
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.
Upvotes: 2
Reputation: 285405
One way:
e.g.,
myDialog.getRootPane().setDefaultButton(exitButton);
Option two:
e.g.,
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);
}
}
Upvotes: 10