1

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
}
Forza
  • 1,619
  • 3
  • 28
  • 49
  • I assume you have the `keyPressed` function because you implemented `KeyEvent`. If all you want to do is the Enter functionality, you dont need that. – davidXYZ Oct 11 '12 at 20:22
  • Remove `inloggenButton.addKeyListener`. You do not need it after adding an action listener. – davidXYZ Oct 11 '12 at 20:48
  • Do `setDefaultButton()` after `initComponents()`. Also, where are you setting your JFrame to visible? You dont have a main function? – davidXYZ Oct 11 '12 at 20:52
  • Hmm that is non-editable code from the gui builder and it won't let me safe delete for some reason.. – Forza Oct 11 '12 at 20:52
  • Main function is in the main class. Do you want me to add it to the OP? – Forza Oct 11 '12 at 20:53
  • In the GUI builder, there should be a way to remove the keyEvent the same way you added it in the 1st place. – davidXYZ Oct 11 '12 at 20:53
  • Just make sure that in your Main class you are getting this JFrame and setting it to visible. – davidXYZ Oct 11 '12 at 20:55
  • I don't know how. Everything I try is blocked by Netbeans... I am beginning to understand now why everyone says I need to use Eclipse in the future – Forza Oct 11 '12 at 20:55
  • I have indd set it to visible in the main ;) – Forza Oct 11 '12 at 20:57
  • 1
    Yes. You are better going through Swing tutorials and doing it by hand. From experience, my first GUI was with Netbeans GUI builder. I got so frustrated and moved all my code to Notepad++ and did it all by hand. The size of your Swing code will also reduce drastically when you depend less on GUI builder. – davidXYZ Oct 11 '12 at 20:59
  • Ok I will certainly do that in the future ;) But for this project it's too late. Things like logging in when pressing enter are the finishing touches. I don't know if you have any more options I can try but if not I suggest we leave it this way. The project works and is nearly finished. Thx for your insintence on helping me though! – Forza Oct 11 '12 at 21:04
  • So, the current problem is: The GUI is showing up but the Enter functionality is not working. Is this correct? – davidXYZ Oct 11 '12 at 21:17
  • Yes that is correct ;) with commenting out the InloggenButtonKeyPressed the enter functionality is not working at all. But @MadProgrammer just posted something promising here, so I will first check tomorrow If I can get this working on my project – Forza Oct 11 '12 at 22:43

3 Answers3

4

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.

davidXYZ
  • 719
  • 1
  • 8
  • 16
  • I already have that implemented.. but doesn't work. Also if I try it exactly like this I get 'package frame does not exist' – Forza Oct 11 '12 at 20:09
  • It depends on how you defined your `JFrame`. Did you create an instance or did you extend it? Your code does not show how you defined your variable `rootPane`. Pls post a more complete code showing the definition and deployment of your frame. – davidXYZ Oct 11 '12 at 20:11
  • I've added the creation of JFrame and JRootPane to the question. That's exactly how I have it now. But maybe I need to tell you that the GUI is build with Netbeans GUI builder. The button is already defined, so that's why I can't say JButton btn = new JButton("Login"); there – Forza Oct 11 '12 at 20:16
  • 1
    Why do you have `rootPane.setDefaultButton(inloggenButton);` in a `keyPressed` event? – davidXYZ Oct 11 '12 at 20:20
  • Also, using Netbeans GUI builder is not a good idea. You'll be better off learning how to write it by hand. Netbeans doesnt let you edit the auto-generated code. – davidXYZ Oct 11 '12 at 20:24
  • I don't know where else to put it. I'm still learning so forgive me if I'm being stupid, but If I place it under JRootPane rootPane = frame.getRootPane(); then I get expected and ; expected.. – Forza Oct 11 '12 at 20:24
  • I know ;) but I have only limited time for this project (for stage for an insurance company) and GUI builder seems to be the fastest option here – Forza Oct 11 '12 at 20:27
  • That's because you are not writing it inside a function, so it's expecting identifier *private/public/protected*. Try putting that line in your main function (before you call `frame.setVisible(true)`). – davidXYZ Oct 11 '12 at 20:29
  • 1
    @Forza this seems to have turned into a different question now which is more about general Java programming. The original question asked has clearly been answered. If you need help with Java I suggest you take a look at tutorials (http://docs.oracle.com/javase/tutorial/) or look at other questions on SO. – Joshua Oct 11 '12 at 20:33
  • davidXYZ you have given me an answer. I haven't got it working yet, but we can move this discussion to chat if you want? – Forza Oct 11 '12 at 20:34
  • From @davidXYZ `Why do you have rootPane.setDefaultButton(inloggenButton); in a keyPressed event?` Yes @Forza, just move that line out of the listener so it is the third line, immediately following `JRootPane rootPane = frame.getRootPane();` -- comment out the whole `inloggenButtonKeyPressed` – Stephen P Oct 11 '12 at 20:35
  • Ok I have done that, but now the entire keypressed event doesn't work anymore. I have moved frame.getRootPane().setDefaultButton(inloggenButton); into the main function and it's accepted there. But what's the final step to get this working? – Forza Oct 11 '12 at 20:38
  • @Forza Sorry, I am not able to chat on my company's computer. – davidXYZ Oct 11 '12 at 20:38
  • 1
    @Forza Please post a full working code from top to bottom. We can only tell where the error is coming from when we see the whole stuff. Update the code in your original question. – davidXYZ Oct 11 '12 at 20:40
  • Ok, check the OP, I have added the whole LoginGUI code to it. – Forza Oct 11 '12 at 20:44
  • @Forza This is why it's important to post a full working example that demonstrates the issue you are having, then we don't have to guess ;) – MadProgrammer Oct 11 '12 at 22:35
2

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);
        }
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

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();
        }
    }
Daniel
  • 1