简体   繁体   中英

Pressing enter on any textfield returns button click

I have a simple jFrame with a loginbutton and I'm trying to fire my ActionPerformed event by pressing the enter key. I don't want to press 'tab' first to focus the button but it should fire whenever someone presses the enter key. What am I missing here?

Edit: If it's easier to do it may also fire the event when the focus is on 'PasswordField' since that's the last field that has the focus before pressing the login button

On request. Here's the full code of the loginGUI:

package unive.facturatie.boundary;

import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import unive.facturatie.control.LoginManager;

/**
 *
 * @author Forza
 */
public class LoginGUI extends javax.swing.JFrame {

JFrame frame = new JFrame();
JRootPane rootPane = frame.getRootPane();
//JButton inloggenButton = new JButton("Login");
//frame.getRootPane().setDefaultButton(inloggenButton);

/**
 * Creates new form LoginGUI
 */
public LoginGUI() {
    frame.getRootPane().setDefaultButton(inloggenButton);
     try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(LoginGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(LoginGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(LoginGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(LoginGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }

    initComponents();
    this.setLocation(320, 160);
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    inlogLabel = new javax.swing.JLabel();
    gebruikersnaamLabel = new javax.swing.JLabel();
    wachtwoordLabel = new javax.swing.JLabel();
    gebruikersnaamTextField = new javax.swing.JTextField();
    wachtwoordPasswordField = new javax.swing.JPasswordField();
    inloggenButton = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Facturatie inlogscherm");

    inlogLabel.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
    inlogLabel.setText("Inloggen");

    gebruikersnaamLabel.setText("Gebruikersnaam:");

    wachtwoordLabel.setText("Wachtwoord:");

    wachtwoordPasswordField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            wachtwoordPasswordFieldActionPerformed(evt);
        }
    });

    inloggenButton.setText("Inloggen");
    inloggenButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            inloggenButtonActionPerformed(evt);
        }
    });
    inloggenButton.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            inloggenButtonKeyPressed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(inlogLabel)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(inloggenButton)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(gebruikersnaamLabel)
                            .addComponent(wachtwoordLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(gebruikersnaamTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)
                            .addComponent(wachtwoordPasswordField)))))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(inlogLabel)
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(gebruikersnaamLabel)
                .addComponent(gebruikersnaamTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(wachtwoordLabel)
                .addComponent(wachtwoordPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(inloggenButton)
            .addContainerGap(25, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void inloggenButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
    //frame.getRootPane().setDefaultButton(inloggenButton);
    boolean isValid = false;
    String username = gebruikersnaamTextField.getText();
    String password = wachtwoordPasswordField.getText();

    LoginManager loginManager = new LoginManager();
    isValid = loginManager.Inloggen(username, password);
    if (isValid == true)
    {
        new MainGUI().setVisible(true);
        dispose();
    }
    else
    {
        JOptionPane.showMessageDialog(frame, "Gebruikersnaam en/of wachtwoord onjuist!", "Insane error", JOptionPane.ERROR_MESSAGE);
    }
}                                              

private void inloggenButtonKeyPressed(java.awt.event.KeyEvent evt) {                                          
      //frame.getRootPane().setDefaultButton(inloggenButton);
      //inloggenButton.registerKeyboardAction(inloggenButton.getActionForKeyStroke(
      //KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false)),
      //KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
      //JButton.WHEN_IN_FOCUSED_WINDOW);

      //inloggenButton.registerKeyboardAction(inloggenButton.getActionForKeyStroke(
      //KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true)),
      //KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
      //JButton.WHEN_IN_FOCUSED_WINDOW);

}                                         

private void wachtwoordPasswordFieldActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
}

// Variables declaration - do not modify
private javax.swing.JLabel gebruikersnaamLabel;
private javax.swing.JTextField gebruikersnaamTextField;
private javax.swing.JLabel inlogLabel;
private javax.swing.JButton inloggenButton;
private javax.swing.JLabel wachtwoordLabel;
private javax.swing.JPasswordField wachtwoordPasswordField;
// End of variables declaration
}

It's quite straightforward:

JFrame frame = new JFrame();
JButton btn = new JButton("Login");
frame.getRootPane().setDefaultButton(btn);

That's it. You do not need a KeyListener , registerKeyBoardAction or getKeyStroke ... Just set an ActionEvent for your button and set that button as default. Pressing Enter when the window is open will activate the default button.

Here's A problem...

Your class extends from JFrame

public class LoginGUI extends javax.swing.JFrame {

But then you create ANOTHER frame within it...

JFrame frame = new JFrame();
JRootPane rootPane = frame.getRootPane();

Then in the constrcutor, you register your button against the "fake" reference

public LoginGUI() {
    frame.getRootPane().setDefaultButton(inloggenButton);

UPDATED

This works just fine...

public class TestDefaultButton {

    public static void main(String[] args) {
        new TestDefaultButton();
    }

    public TestDefaultButton() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestForm());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    protected class TestForm extends JPanel {

        private JButton myDefault;
        private JTextField myText;

        public TestForm() {
            myDefault = new JButton("By Default");
            myDefault.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(TestForm.this, "By default");
                }
            });

            myText = new JTextField(12);

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.insets = new Insets(8, 8, 8, 8);

            add(myText, gbc);

            gbc.gridy++;
            add(myDefault, gbc);
        }

        @Override
        public void addNotify() {
            super.addNotify();
            SwingUtilities.getRootPane(this).setDefaultButton(myDefault);
        }
    }
}

in my project i use this simple code using netbeans:

    private void txt_passwordKeyPressed(java.awt.event.KeyEvent evt)
    {                                    
        if (evt.getKeyCode()==KeyEvent.VK_ENTER){
        btn_login.doClick();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM