在Java GUI中同时从鼠标和键盘输入

时间:2012-09-26 19:20:26

标签: java user-interface mouseevent actionlistener keyboard-events

我需要让java中的GUI同时响应鼠标和键盘的输入..我知道我应该在动作监听器中添加一些东西但是没有找到正确的想法..有什么建议吗?< / p>

我需要让我的GUI响应鼠标移动和点击,同时响应键盘按钮,如果鼠标悬停在按钮上并按下输入.. GUI将响应键盘和鼠标动作操作会继续正常!!希望问题得到解决!

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

看看Toolkit.addAWTEventLstener

这将允许您监视流经事件队列的所有事件。

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

答案 2 :(得分:0)

为了让按钮响应鼠标的行为输入被按下,我会:

  • 使用附加到JButton的Key Binding来允许它响应回车键。
  • 确保在执行上述操作时使用与JComponent.WHEN_IN_FOCUSED_WINDOW常量关联的InputMap,以便按钮实际上不必具有焦点以响应但需要位于焦点窗口中。
  • 当然绑定到与KeyEvent.VK_ENTER关联的KeyStroke。
  • 在键绑定操作中,通过调用模型上的isRollOver()来检查按钮的模型是否处于rollOver状态。
  • 如果是,请回复。
  • 请注意,以上都不需要MouseListener,因为我使用的是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();
         }
      });
   }
}
相关问题