I have a JFrame
with three JButtons on it. I have set txtSearch
(a JTextField
component) to have the focus when JFrame
loads. One of the buttons is set as the default button. This is my code:
private void formWindowOpened(java.awt.event.WindowEvent evt)
{
// btnRefresh.setMnemonic(KeyEvent.VK_R); // Even if this line
// is not commented, but
// still the event wouldn't fire.
this.getRootPane().setDefaultButton(btnRefresh);
}
When it loads, the button is just selected, but it did nothing when the Enter key was being pressed. How do I correctly implement it?
btnRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRefreshActionPerformed(evt);
}
});
private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(this, "Pressed!");
// Other codes here (Replace by JOptionPane)
}
You can use super. dispose() method which is more similar to close operation. Show activity on this post. You cat use setVisible () method of JFrame (and set visibility to false ) or dispose () method which is more similar to close operation.
the code will show the "Add button is pressed" message when I press "Checkout" button after I press "Add" button but If the "Add" Button is not pressed before the "Checkout" Button is pressed, the code will show the "Add Button is not pressed" message.
What component has focus when the JFrame
comes up? I ask because some components "eat" the Enter key event. For example, a JEditorPane
will do that.
Also, when you assign an ActionListener
to JTextField
, the ActionListener
will be called instead of the DefaultButton
for the root pane. You must choose either to have an ActionListener
or a DefaultButton
, but you can't have both fire for the same JTextField
. I'm sure this applies to other components as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With