我需要一个检查鼠标光标是否在组件上的函数。这些组件将是JButton
,JTextField
和JLabel
。我试过以下代码
@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);
}
}
}
}
答案 0 :(得分:0)
Java中有一个名为Mouse Listener
的函数,您可以使用它。您可以单独将它添加到组件中,然后当鼠标越过组件时,将发生MouseEvent
。例如,如果您有JButton
名为yourComponent
,则可以将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
"