有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用户界面在JavaGUI中同时从鼠标和键盘获取输入

我需要让java中的GUI同时响应鼠标和键盘输入。。我知道我应该在action listener的循环中添加一些内容。。但是没有找到正确的想法。。有什么建议吗

我需要让我的GUI响应鼠标移动和单击,同时响应键盘按钮按下,如果鼠标位于按钮上方并按下enter。。GUI将响应键盘,鼠标运动动作将正常继续。。希望问题解决


共 (3) 个答案

  1. # 1 楼答案

    要获得鼠标在按下按钮时的响应行为,我将:

    • 使用附加到JButton的键绑定允许它响应enter键
    • 确保在执行上述操作时,使用与JComponent.WHEN_IN_FOCUSED_WINDOW常量关联的InputMap,以便按钮实际上不必具有焦点才能响应,而是需要位于焦点窗口中
    • 当然,绑定到与KeyEvent关联的击键。请进来
    • 在键绑定操作中,通过调用模型上的isRollOver(),检查按钮的模型是否处于滚动状态
    • 如果是的话,请回答
    • 请注意,以上这些都不需要鼠标侦听器,因为我使用ButtonModel的isRollOver来代替鼠标侦听器

    例如,我的SSCCE:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    
    import javax.swing.*;
    
    public class MouseKeyResponse extends JPanel {
       private JButton button = new JButton("Button");
    
       public MouseKeyResponse() {
          button.addActionListener(new ActionListener() {
    
             @Override
             public void actionPerformed(ActionEvent e) {
                System.out.println("button clicked");
             }
          });
          add(button);
    
          setUpKeyBindings(button);
       }
    
       private void setUpKeyBindings(JComponent component) {
          int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
          InputMap inputMap = component.getInputMap(condition);
          ActionMap actionMap = component.getActionMap();
    
          String enter = "enter";
          inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), enter);
          actionMap.put(enter, new EnterAction());
       }
    
       private class EnterAction extends AbstractAction {
          @Override
          public void actionPerformed(ActionEvent evt) {
             if (button.isEnabled() && button.getModel().isRollover()) {
                System.out.println("Enter pressed while button rolled over");
                button.doClick();
             }
          }
       }
    
       private static void createAndShowGui() {
          MouseKeyResponse mainPanel = new MouseKeyResponse();
    
          JFrame frame = new JFrame("MouseKeyResponse");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    
  2. # 2 楼答案

    看一看Toolkit.addAWTEventLstener

    这将允许您监视事件队列中的所有事件

    您将遇到的问题是识别有效区域中的组件并克服组件的默认行为(在文本字段具有焦点时按enter键将触发其上的操作事件,但现在您想做其他事情)

  3. # 3 楼答案

    您不必“在循环中添加某些内容”。您只需将MouseListenerKeyListener添加到GUI元素(例如框架)中,并根据需要实现回调方法