我有一个扩展JPanel的外部类,它拥有一个只绘制图像的paintComponent方法,我的内部类也是一个JPanel,是我的鼠标事件监听器。事件通过在更改后调用重绘来改变绘图的外观,但看起来似乎没有正确调用重绘
public class FollowingEyes extends JPanel
{
private Eye eye;
private Eye eye2;
private final int HEIGHT = 500;
private final int WIDTH = 500;
private OtherPanel panel;
public FollowingEyes()
{
eye = new Eye((WIDTH/2)-50,50);
eye2 = new Eye((WIDTH/2)+50,50);
panel = new OtherPanel();
setPreferredSize(new Dimension(500,500));
addMouseListener(panel);
addMouseMotionListener(panel);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
eye.draw(g);
eye2.draw(g);
}
private class OtherPanel extends JPanel implements MouseListener, MouseMotionListener
{
@Override
public void mouseEntered(MouseEvent e)
{
System.out.println("Mouse entered..");
eye.look(true);
eye2.look(true);
repaint();
}
@Override
public void mouseExited(MouseEvent e)
{
System.out.println("Mouse exited..");
eye.look(false);
eye2.look(false);
repaint();
}
@Override
public void mouseClicked(MouseEvent e){};
@Override
public void mousePressed(MouseEvent e){};
@Override
public void mouseReleased(MouseEvent e){};
@Override
public void mouseMoved(MouseEvent e)
{
eye.setAngle(e.getX(), e.getY());
eye2.setAngle(e.getX(), e.getY());
repaint();
}
@Override
public void mouseDragged(MouseEvent e){};
}
答案 0 :(得分:1)
问题在于您的眼睛(eye
和eye2
)已添加到FollowingEyes
面板中,但移动鼠标后,您会在{{1}上调用repaint()
因此,眼睛不会被重新粉刷。
尝试调用OtherPanel
实例的repaint()
:
FollowingEyes
另一个问题是eyes.repaint();
的{{1}}属性是用新的eyes
实例初始化的,而不是用封闭的实例初始化的。您应该使用OtherPanel
对其进行初始化,或者将其作为构造函数参数传递(这样您就可以将FollowingEyes
类作为外部类)。
答案 1 :(得分:1)
首先,字段eyes
未被使用,因此无效。另外,如果您要从FollowingEyes
调用整个OtherPanel
上的重绘,请使用FollowingEyes.this.repaint()
。您目前所拥有的只是重新粉饰 OtherPanel
。