I have created simple fragment of code to demonstrate some strange stuff with JAVA.
public class Start extends JFrame {
public static JFrame mainFrame;
public static void main(String[] args) {
JFrame f = new JFrame();
mainFrame = f;
f.setSize(400, 400);
Action btn_action = new AbstractAction() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("test");
JDialog d = new JDialog(mainFrame, "Test Dialog", true);
d.setSize(200, 200);
d.setLocationRelativeTo(null);
JTextField text = new JTextField();
d.add(text);
d.setVisible(true);
}
};
JButton btn = new JButton(btn_action);
btn.setText("Click me");
KeyStroke btnShortcut = KeyStroke.getKeyStroke(KeyEvent.VK_1, 0);
btn.getActionMap().put("btn_click", btn_action);
btn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(btnShortcut, "btn_click");
f.add(btn);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
I have JFrame component with a JButton on it. JButton has a shortcut (keyboard number 1).
When I press 1 on top row of keyboard, action is performing. It's creating JDialog in action with one component on it - JTextField. So about what's strange
When I press 1, that number sometimes prints in JTextField area of JDialog. It's happening sometimes. It seems to be taken from the keyboard buffer.
How can it be cleared before JDialog is opening ? Or is there another solution ?
Thanks in advance.
-
I am unable to reproduce this issue. How to replicate it?Braj– Braj2014年06月13日 14:04:35 +00:00Commented Jun 13, 2014 at 14:04
-
Okay, I see the problem you mean. I can reproduce it.Rudi Kershaw– Rudi Kershaw2014年06月13日 14:10:33 +00:00Commented Jun 13, 2014 at 14:10
-
@ZerO That would be VK_NUMPAD1mttdbrd– mttdbrd2014年06月13日 14:15:06 +00:00Commented Jun 13, 2014 at 14:15
-
@tvolf: since your JDialog is modal, it will have focus and any subsequent key press will enter the value in Jtextfiled.Shailesh Aswal– Shailesh Aswal2014年06月13日 15:27:47 +00:00Commented Jun 13, 2014 at 15:27
-
@Shail016: Why is JDialog catching key presses that were sent by button at JFrame but not JDialog ?tvolf– tvolf2014年06月13日 18:04:56 +00:00Commented Jun 13, 2014 at 18:04
1 Answer 1
Try binding to the key release event, rather than the key press event, so that the key has been definitely released by the time the dialog opens:
KeyStroke btnShortcut = KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, true);
^^^^