问题
I am trying to do a mouseEntered test to change a square colour however the MouseListener mouseEntered would not execute. The mouse is responding but only to clicks, pressed and release. So i am not sure what is going on. I hope you can help me point my problem thanks.
//Class
class RectangleClass extends JPanel{
private int height;
private int width;
private boolean MouseEntered= false;
private boolean MouseExit= false;
private JPanel myPanel = new JPanel();
//Inner class with mouse Event
class RectangleAdapter extends MouseAdapter{
public void MouseEntered(MouseEvent e){
System.out.println("MouseEntered");
MouseEntered = true;
repaint();
}
public void MouseExited(MouseEvent e){
System.out.println("MouseExited");
MouseExit = true;
repaint();
}
}
//constructor
public RectangleClass(int height,int width){
myPanel = this;
this.height=height;
this.width=width;
this.addMouseListener(new RectangleAdapter());
}
//paint graphic
public void paint(Graphics g){
super.paint(g);
g.clearRect(0, 0, width, height);
g.drawRect(0, 0, width, height);
g.setColor(Color.YELLOW);
if (MouseEntered){
g.setColor(Color.CYAN);
MouseEntered= false;
}
if (MouseExit){
g.setColor(Color.orange);
MouseExit= false;
}
g.fillRect(0, 0, width, height);
}
}
public class RectangleContainer extends JFrame{
public RectangleContainer(){
setLayout(null);
JPanel myPanel = new RectangleClass(100,100);
myPanel.setBounds(50, 50, 200, 200);
setSize(200,200);
add(myPanel);
setVisible(true);
}
public static void main(String args[]){
new RectangleContainer();
}
}
回答1:
You have started the mouseEntered
method in your code with a capital M. Change it to lowercase m.
回答2:
You're not actually overriding the mouseEntered method of MouseAdapter
, you need
@Override
public void mouseEntered(MouseEvent e) {
Adding @Override
will let the compiler check that you are overriding the correct method. The same applies for mouseExited BTW.
Side Notes:
- Don't use null layout - Always use a layout manager
- For custom painting override
paintComponent
rather thanpaint
- Java naming conventions indicate that all variables start with a lowercase letter which would make the variable
MouseEntered
mouseEntered
来源:https://stackoverflow.com/questions/15457160/mouseentered-will-not-execute