javaswingevent-handlingdefaultbutton

How to set the Java default button to react on ENTER key _released_?


In my application I use a Default button. I want it to react when ENTER Key is released. Not when ENTER Key is pressed.

I removed the KeyStroke from InputMap of the button. But it didn't work for me. How should i do that?


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class ButtonTest {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                buildFrame();
            }
        });
    }

    private static void buildFrame() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JButton button = new JButton(new AbstractAction("Button") {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("ButtonTest::actionPerformed: CALLED");
            }
        });

        JButton button2 = new JButton("Button 2");
        InputMap im = button.getInputMap();
        im.put(KeyStroke.getKeyStroke("ENTER"), "none");
        im.put(KeyStroke.getKeyStroke("released ENTER"), "released");

        f.setLayout(new GridBagLayout());
        f.add(button);
        f.add(button2);
        f.getRootPane().setDefaultButton(button);

        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}

This is the sample code.


Solution

  • JRootPane rootPane = SwingUtilities.getRootPane(/* Your JButton  */); 
    rootPane.setDefaultButton(/* Your JButton  */);