检查鼠标光标是否在组件上

Check whether the cursor of a mouse is over a component

我需要一个函数来检查鼠标光标是否在组件上。这些组件将是 JButtonJTextFieldJLabel。我试过下面的代码

@Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        boolean noDraw = false;

        if(this.getWidth() > mX && mX > 0){
            if( this.getHeight() > mY && mY > 0){
               components = this.getComponents();
               if( components != null){
                   for(int i = 0; i < components.length; ++i){
                      if( components[i].contains(mX, mY)){
                          noDraw = true;
                          break;
                      }
                   }
               }
               if(noDraw == false )
               {
                   Cicle.draw(g);
               }
            }
        }

    }

Java 中有一个名为 Mouse Listener 的函数,您可以使用它。您将它单独添加到组件中,然后当鼠标经过组件时会出现 MouseEvent。例如,如果您有一个名为 yourComponentJButton,您可以像这样将 Mouse Listener 添加到组件中。

yourComponent.addMouseListener(new CustomMouseListener());

class CustomMouseListener implements MouseListener
{
    @Override
    public void mouseClicked(MouseEvent e){}

    @Override
    public void mouseEntered(MouseEvent e)
    {
        //Mouse is over component
        Object source = e.getSource();
        if (source instanceof JButton) {
            System.out.println("Mouse is over a JButton");
        }

        if (source instanceof JTextField) {
            System.out.println("Mouse is over a JTextField");
        }

        if (source instanceof JLabel) {
            System.out.println("Mouse is over a JLabel");
        }

        Sysem.out.println("Mouse is over "+ e.getComponent().getClass().getName());
    }

    @Override
    public void mouseExited(MouseEvent e)
    {
         //Mouse is not over component
         Sysem.out.println("Mouse is not over "+ e.getComponent().getClass().getName()+" anymore");
    }

    @Override
    public void mousePressed(MouseEvent e){}

    @Override
    public void mouseReleased(MouseEvent e){}
}

有关它们如何工作的更多信息,请参阅 "How to write a Mouse Listener"