一尘不染

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

java

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

KeyStrokeInputMap按钮中删除了。但这对我没有用。我该怎么办?


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

这是示例代码。


阅读 238

收藏
2020-12-03

共1个答案

一尘不染

JRootPane rootPane = SwingUtilities.getRootPane(/* Your JButton  */); 
rootPane.setDefaultButton(/* Your JButton  */);
2020-12-03