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

2022-09-02 11:54:25

在我的应用程序中,我使用默认按钮。我希望它在释放 Key 时做出反应。按下键时不可以ENTERENTER

我删除了按钮的。但它对我不起作用。我该怎么做?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);
    }
}

这是示例代码。


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

答案 2

默认按钮的键(即,在 enter 时触发的按钮,无论哪个组件是 focusOwner)绑定在 rootPane 的组件 InputMap 中,即其WHEN_IN_FOCUSED_WINDOW类型的 inputMap。所以从技术上讲,这是调整的地方:

JComponent content = new JPanel();
content.add(new JTextField("some focusable"));
content.add(new JTextField("something else"));

JXFrame frame = wrapInFrame(content, "default button on released");
Action action = new AbstractAction("do something") {

    @Override
    public void actionPerformed(ActionEvent e) {
        LOG.info("clicked");
    }
};
JButton button = new JButton(action);
content.add(button);
frame.getRootPane().setDefaultButton(button);
// remove the binding for pressed
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
    .put(KeyStroke.getKeyStroke("ENTER"), "none");
// retarget the binding for released
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
    .put(KeyStroke.getKeyStroke("released ENTER"), "press");

请注意:这仍然与非默认按钮的按下/释放行为不同,因为rootPane操作只是调用的butle.doClick,而无需通过武装/按下buttonModel的动作来间接触发操作。


推荐