[英]Affecting Boolean Variables with Mouse Events Using Swing
I am not sure why the mouse events set by my mouse listener are not affecting whether or not the hat is drawn. 我不确定为什么我的鼠标监听器设置的鼠标事件不会影响是否绘制了帽子。 The variable "mouseInside" seems not to be affected by the mouse events.
变量“mouseInside”似乎不受鼠标事件的影响。 How do I change the variable to false with the mouse events?
如何使用鼠标事件将变量更改为false?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.*;
public class EyesOpen extends JPanel{
private Ellipse2D.Double head;
private Ellipse2D.Double eyeOne;
private Ellipse2D.Double eyeTwo;
private Rectangle2D.Double hatBody;
boolean mouseInside;
public EyesOpen(){
this.setFocusable(true);
this.requestFocus();
this.setPreferredSize(new Dimension(500,500));
head = new Ellipse2D.Double(180,180,140,140);
eyeOne = new Ellipse2D.Double(220,220,20,20);
eyeTwo = new Ellipse2D.Double(260,220,20,20);
hatBody = new Rectangle2D.Double(170,180,160,20);
class MyMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e){
mouseInside=true;
}
public void mouseExited(MouseEvent e){
mouseInside=false;
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
}
this.addMouseListener(new MyMouseListener());
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(Color.BLUE);
g2.fill(head);
g2.setPaint(Color.BLACK);
g2.fill(eyeOne);
g2.setPaint(Color.BLACK);
g2.fill(eyeTwo);
if(mouseInside=true){
g2.setPaint(Color.BLACK);
g2.fill(hatBody);}
}
public static void main(String[] args){
JFrame f = new JFrame("Head");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLayout(new FlowLayout());
f.add(new EyesOpen());
f.pack();
f.setVisible(true);
}
}
Don't forget to call repaint()
after changing the boolean. 不要忘记在更改布尔值后调用
repaint()
。
To be precise, you could specify that it is the drawing component's method that gets called via EyesOpen.this.repaint();
确切地说,您可以指定它是通过
EyesOpen.this.repaint();
调用的绘图组件的方法EyesOpen.this.repaint();
, but this isn't absolutely necessary in this current program (I don't think). ,但这在目前的计划中并非绝对必要(我不认为)。
Other nitpicks: 其他挑剔:
paintComponent(...)
method should be specified as protected
not public
. paintComponent(...)
方法应指定为protected
而不是public
。 No sense in exposing it any more than it needs to be exposed. @Override
annotation any time that you think that you're overriding a method. @Override
注释。 While it may not matter with this program, it will save your behind in the future. SwingUtilities.invokeLater(/** Your Runnable Goes Here **/);
SwingUtilities.invokeLater(/** Your Runnable Goes Here **/);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.