使用空格键触发JButton,或输入键或鼠标单击 [英] Fire a JButton with spacebar, or enter key, or mouse click

查看:158
本文介绍了使用空格键触发JButton,或输入键或鼠标单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用单个按钮获取一个简单的JFrame,以便在发生任何这些事件时触发事件:

I'm trying to get a simple JFrame with a single button to fire an event when any of these events happen:


  • 按Enter键并且JButton具有焦点

  • 按下空格键并且JButton具有焦点

  • 单击JButton。

似乎Enter和空格键是免费,以及使用JButton上的addActionListener默认鼠标点击;麻烦的是,我已经读过,键绑定依赖于所使用的外观。

It seems that the Enter and Spacebar come "for free" along with the default mouse click using addActionListener on the JButton; trouble is, I've read that the the key bindings are dependent on the Look and Feel used.

我试图通过添加Enter来实现跨LaF的通用行为空格键到JButton的动作图,甚至添加了一个随机键(m)来确保ActionMap正在进行工作(它是),但现在鼠标点击丢失了。我似乎能够获得所有键和鼠标单击的唯一方法是使用动作映射和addActionListener。

I've tried to get universal behavior across LaF by adding Enter and Spacebar to the JButton's action map, and even added a random key ("m") to make sure the ActionMap was doing the work (it was), but now the mouse click is lost. The only way I seem to be able to get all the keys and mouse click is to use both action map and addActionListener.

有没有办法获取这些键和鼠标绑定在所有LaF中一致地工作而不试图检测可能出现的每个可能的LaF?我可以注册一个动作侦听器,它将触发键和鼠标事件吗?

Is there a way to get these key and mouse bindings to work consistently across all LaF without trying to detect every possible LaF that may come along? Can I register a single action listener that will fire on both key and mouse events?

我最喜欢的解决方案是在JButton动作图中添加鼠标点击,并检测动作内部发生的键或鼠标点击。

My favorite solution would be to add a mouse click to the JButton action map and detect which key or mouse click happened inside the inside the action.

我还在这里学习绳索,所以这可能不是最好或最有效的做事方式;我确信它过度设计了。这是一种训练练习,我正在试验我能掌握的一切。欢迎任何和所有编码风格的评论!

I'm still learning the ropes here, so this probably isn't the best or most efficient way to do things; I'm sure it's over-engineered. This is sort of training exercise where I'm experimenting with everything I can get my hands on. Any and all coding style comments are welcome!

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;

public class Example extends JFrame {

// ============================
private class BtnListener extends AbstractAction {
    private static final long serialVersionUID = 1L;

    public void actionPerformed(ActionEvent ae) {
        System.out.println("\nclick button listener triggered");
        System.out.println(ae.getSource().getClass().toString());
    }
} // class BtnListener

private static final int NO_MODIFIER = 0;
private static final boolean ON_KEY_PRESS = false;
private static final KeyStroke ENTER_PRESSED = KeyStroke.getKeyStroke(
        KeyEvent.VK_ENTER, NO_MODIFIER, ON_KEY_PRESS);
private static final KeyStroke M_PRESSED = KeyStroke.getKeyStroke(
        KeyEvent.VK_M, NO_MODIFIER, ON_KEY_PRESS);
private static final KeyStroke SPACEBAR_PRESSED = KeyStroke.getKeyStroke(
        KeyEvent.VK_SPACE, NO_MODIFIER, ON_KEY_PRESS);
private JButton btnButton;
private final AbstractAction btnListener = new BtnListener();
private JPanel buttonPanel;
private JFrame frmMain;

public static void main(String[] args) {
    Example ex = new Example();
    ex.displayFrame();
}

Action btnActionListener = new AbstractAction() {
    private static final long serialVersionUID = 1L;

    public void actionPerformed(ActionEvent e) {
        System.out.println("\nkey button action triggerred");
        System.out.println(e.getSource().getClass().toString());
        if (e.getSource() instanceof JButton) {
            System.out.println("button");
        } else {
            System.out.println("Something else");
        }
    }
};

public Example() {
    initialize();
}

public void displayFrame() {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Throwable e) {
        e.printStackTrace();
    }
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                frmMain.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

private void initialize() {

    frmMain = new JFrame();
    btnButton = new JButton("Abutton");

    // Comment this out, you lose the mouse click
    btnButton.addActionListener(btnListener);

    // Comment out ActionMaps, but keep addActionListner (above), and
            // only lose M_PRESSED
    InputMap buttonFocusedMap = btnButton
            .getInputMap(JComponent.WHEN_FOCUSED);

    buttonFocusedMap.put(ENTER_PRESSED, "blah");
    btnButton.getActionMap().put("blah", btnActionListener);

    buttonFocusedMap.put(SPACEBAR_PRESSED, "blort");
    btnButton.getActionMap().put("blort", btnActionListener);

    buttonFocusedMap.put(M_PRESSED, "gaaak");
    btnButton.getActionMap().put("gaaak", btnActionListener);

    // Is there a way to add a mouse click to the ActionMap?

    buttonPanel = new JPanel();
    buttonPanel.add(btnButton);

    frmMain.getContentPane().add(buttonPanel);
    frmMain.setBounds(100, 100, 500, 432);
    frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}


推荐答案

BasicButtonUI 使用的

BasicButtonListener 确保所有按钮(检查,收音机) ,toggle)在聚焦时绑定到 Space 。这适用于跨平台,即使个人外观和感觉可以唯一地呈现各种按钮模型状态。按 Space 会唤起按下 <$ em $ c> UIAction ,并释放 Space 会唤起发布 UIAction 。在按钮界限内按下并释放鼠标时也会出现同样的情况;在按下时拖动按钮以查看布防状态更改。

BasicButtonListener, used by BasicButtonUI, ensures that all buttons (check, radio, toggle) are bound to Space when focused. This works across platforms, even though individual Look & Feels may render various button model states uniquely. Pressing Space evokes the pressed UIAction, and releasing Space evokes the released UIAction. The same occurs when the mouse is pressed and released within the button's bounds; drag outside the button while pressed to see the armed state change.

在任何一种情况下,按下的组合已发布调用你的按钮的 actionPerformed()方法。

In either case, the combination of pressed and released invokes your button's actionPerformed() method.

一种方便的方法来绑定 Enter 无论焦点如何,都是 Action 是通过根窗格的 setDefaultButton() 方法。此示例说明了点击按钮的所有三种方法。

One convenient way to bind Enter to an Action, irrespective of focus, is via the root pane's setDefaultButton() method. This example illustrates all three ways to click a button.

这篇关于使用空格键触发JButton,或输入键或鼠标单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆