Search code examples
javaswinghotkeysenter

How to add a hotkey Enter in a JPanel class?


First, I know how to add an Enter hotkey with the following code:

JPanel panel = new JPanel();
//...
JButton button = new JButton("Execute");
panel.getRootPane().setDefaultButton(button); // Hotkey "Enter" by default
// ...
panel.add(button);

But in this case, the following code below

class LeftPanel extends JPanel
{
    LeftPanel()
    {
        setLayout(null);
        setBounds(2, 42, 146, 252);

        button();
    }

    void button() 
    {       
        JButton exebutton = new JButton("Execute");
        //getRootPane().setDefaultButton(exebutton); // Hotkey "Enter" by default
        exebutton.setMnemonic(KeyEvent.VK_ENTER); // Shortcut: Alt + Enter
        exebutton.setBounds(4, 18, 138, 47);
        add(exebutton);
    }
}

How do I add the Enter hotkey? getRootPane().setDefaultButton(exebutton); does not work. I got an error :

Exception in thread "main" java.lang.NullPointerException

This is my frame class

public class MyFrame extends JFrame
{   
    MyFrame()
    {
        setTitle("Frame Test");
        setSize(400, 200);
        setLayout(null);

        LeftPanel leftpanel = new LeftPanel();
        add(leftpanel);

        setVisible(true);
        setDefaultCloseOperation(MyFrame.EXIT_ON_CLOSE);
    }
}

and my main

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

Alt+Enter shortcut works, but not Enter.


Solution

  • Add the getRootPane().setDefaultButton(exebutton); in your MyFrame class like this

    public class MyFrame extends JFrame
    {   
        MyFrame()
        {
            setTitle("Frame Test");
            setSize(400, 200);
            setLayout(null);
    
            LeftPanel leftpanel = new LeftPanel();
            add(leftpanel);
            getRootPane().setDefaultButton(leftpanel.getDefaultBtn());
    
            setVisible(true);
            setDefaultCloseOperation(MyFrame.EXIT_ON_CLOSE);
        }
    }
    

    Make sure you can access your JButton by declaring it before any of the methods like so

    class LeftPanel extends JPanel
    {
        JButton exeButton;
    
        LeftPanel()
        {
            setLayout(null);
            setBounds(2, 42, 146, 252);
    
            button();
        }
    
        void button() 
        {       
            exebutton = new JButton("Execute");
            exebutton.setMnemonic(KeyEvent.VK_ENTER); // Shortcut: Alt + Enter
            exebutton.setBounds(4, 18, 138, 47);
            add(exebutton);
        }
    
        public JButton getDefaultBtn()
        {
            return exebutton;
        }
    }