同时进行MouseEnter和KeyPressing Java Swing [英] MouseEntered and KeyPressed at Same Time Java Swing

查看:89
本文介绍了同时进行MouseEnter和KeyPressing Java Swing的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java Swing,我有20个JLabels.每个JLabel都有一个MouseListenerKeyListener.我一直在试图找到一种方法(没有运气),以便能够知道鼠标已输入/悬停在哪个标签上以及何时按下了删除键.

Using Java Swing I have 20 JLabels. Each JLabel has a MouseListener and a KeyListener. I'm been trying to come up with a way (with no luck) to be able to know which label the mouse has entered/hovering over and when the delete key is pressed.

例如,当按下Delete键并且鼠标位于JLabel 5中时,我希望对JLabel 5进行操作.

For instance, when the delete key is pressed and the mouse is in JLabel 5. I want an action on JLabel 5 to be performed.

我知道如何独立使用MouseListenerKeyListener,但是我不知道如何像这样一起使用它们.

I know how to use MouseListener and KeyListener independently, but I don't know how to use them together like that.

这就是我正在尝试做的事.

Here is what I'm attempting to do.

    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_DELETE){
            //Get the JLabel that the mouse has entered/hovering over
            //Perform action on that JLabel

        }
    }

如果有关系,我将使用所有JLabel的列表.

In case it matters, I'm using a List for all of the JLabel's.

推荐答案

建议可能会让您感到惊讶:

Suggestions that might surprise you:

  • 惊奇数字1:不要使用MouseListener
  • 惊奇数字2:不要使用MouseMotionListener.
  • 惊喜3:不要使用KeyListeners.
  • 代替使用键绑定(此处的教程:键绑定教程).我建议您在保存JLabel网格的JPanel上绑定Delete键.然后,当按下Delete键时,通过使用MouseInfo类获取PointerInfo实例来找出光标在哪个JLabel上(如果有),并使用该实例获取光标在屏幕上的位置.有了这些信息和一些简单的数学运算,您应该很容易找出哪个标签具有光标(再次,如果有的话),并采取适当的措施.请注意,键绑定"教程将告诉您为什么使用这些键而不是使用KeyListeners更好,但是最重要的是,您不必花太多时间关注应用程序的焦点.
  • Surprise number 1: Don't use a MouseListener
  • Surprise number 2: Don't use a MouseMotionListener.
  • Surprise number 3: Don't use KeyListeners.
  • Instead use Key Bindings (tutorial here: Key Bindings Tutorial). I suggest that you bind the delete key press on the JPanel that holds your grid of JLabel. Then when the delete key has been pressed, find out which JLabel the cursor is over (if any) by using the MouseInfo class to get a PointerInfo instance, and with that get the location of the cursor on the screen. With that information and some trivial math, it should be easy for you to figure out which label has the cursor (again, if any), and do your appropriate action. Note that the Key Bindings tutorial will tell you why its better to use these rather than KeyListeners, but most importantly, you don't have to futz so much with the application's focus.

修改 例如:

import java.awt.Component;
import java.awt.GridLayout;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class BindingExample extends JPanel {
   private static final int ROWS = 10;
   private static final int COLS = 8;
   JLabel[][] labels = new JLabel[ROWS][COLS];

   public BindingExample() {
      setLayout(new GridLayout(ROWS, COLS));
      for (int r = 0; r < labels.length; r++) {
         for (int c = 0; c < labels[r].length; c++) {
            String labelText = String.format("[%d,  %d]", r, c);
            labels[r][c] = new JLabel(labelText, SwingConstants.CENTER);
            int eb = 4;
            labels[r][c].setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
            add(labels[r][c]);
         }
      }

      int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();

      KeyStroke delKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
      String delete = "delete";

      inputMap.put(delKeyStroke, delete);
      actionMap.put(delete, new DeleteAction());
   }

   private class DeleteAction extends AbstractAction {
      @Override
      public void actionPerformed(ActionEvent evt) {
         PointerInfo pInfo = MouseInfo.getPointerInfo();
         Point ptOnScrn = pInfo.getLocation();
         int xPanel = getLocationOnScreen().x;
         int yPanel = getLocationOnScreen().y;
         int x = ptOnScrn.x - xPanel;
         int y = ptOnScrn.y - yPanel;

         Component component = getComponentAt(x, y);
         if (component != null) {
            JLabel selectedLabel = (JLabel) component;
            System.out.println("Selected Label: " + selectedLabel.getText());
         }
      }
   }

   private static void createAndShowGui() {
      BindingExample mainPanel = new BindingExample();

      JFrame frame = new JFrame("Key Bindings Example");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_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
射击,只看到您的问题的评论,是的,对于您的目的而言,JList可能会更好.


Edit 2
Shoot, just saw the comments to your question, and yeah, a JList would probably be much better for your purposes.

这篇关于同时进行MouseEnter和KeyPressing Java Swing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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