Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default button in JFrame is not firing when the enter key is being pressed

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)
}  
like image 848
John Woo Avatar asked Mar 08 '12 02:03

John Woo


People also ask

How do you make a JFrame close when a button is pressed?

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.

How do I know if JButton is pressed?

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.


1 Answers

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.

like image 69
Chuck Krutsinger Avatar answered Oct 14 '22 04:10

Chuck Krutsinger