MouseEntered and KeyPressed at Same Time Java Swing

前端 未结 2 965
梦谈多话
梦谈多话 2021-01-21 22:50

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

2条回答
  •  甜味超标
    2021-01-21 23:31

    In the top of your class:

    private JLabel hoveredLabel;

    When adding a JLabel:

    final JLabel label = ...
    
    label.addMouseMotionListener(new MouseListener() {
        ...
    
        public void mouseEntered(MouseEvent me) {
            hoveredLabel = (JLabel)me.getSource();
        }
    
        public void mouseExited(MouseEvent me) {
            hoveredLabel = null;
        }
    }
    

    And your KeyListener:

    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
            if (hoveredLabel != null)
                doSomethingWith(hoveredLabel);
        }
    }
    

    Make sure you add the KeyListener to the contentPane of the JFrame.

提交回复
热议问题