如何设置 Java 默认按钮以对 ENTER 键 _released_ 做出反应?

2022-01-15 00:00:00 event-handling java swing defaultbutton

在我的应用程序中,我使用默认按钮.我希望它在 ENTER 键释放时做出反应.不是当 ENTER 键被按下.

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

我从按钮的 InputMap 中删除了 KeyStroke.但这对我不起作用.我该怎么做?

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);
    }
}

这是示例代码.

推荐答案

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

相关文章