[英]unable to call repaint from inner class
I have a outer class which extends JPanel and holds a paintComponent method which just draws an image, my inner class is also a JPanel and is my mouse event listener. 我有一个外部类,它扩展了JPanel并拥有一个paintComponent方法,该方法仅绘制图像,我的内部类也是一个JPanel,并且是我的鼠标事件侦听器。 The events change the way the drawing looks by calling the repaint after the changed, but it doesn't seem like the repaint is getting called properly
这些事件通过在更改后调用重新绘制来更改图形的外观,但是似乎未正确调用重新绘制
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){};
}
The problem is that your eyes ( eye
and eye2
) are added to the FollowingEyes
panel but when mouse is moved, you call repaint()
on the OtherPanel
thus eyes will not be repainted. 问题是您的眼睛(
eye
和eye2
)已添加到“ FollowingEyes
面板中,但是当鼠标移动时,您在OtherPanel
上调用repaint()
,因此不会重新绘制眼睛。
Try calling repaint()
of the FollowingEyes
instance: 尝试调用
repaint()
的的FollowingEyes
实例:
eyes.repaint();
Also another problem is that the eyes
attribute of OtherPanel
is initialized with a new FollowingEyes
instance and not with the enclosing instance. 另外一个问题是,
eyes
的属性OtherPanel
与新初始化FollowingEyes
实例,并没有与外围实例。 You should initialize it with FollowingEyes.this
or pass it as a constructor argument (that way you will be able to make the OtherPanel
class an external class). 你应该初始化它
FollowingEyes.this
或者把它作为一个构造函数的参数(这样你就能够使OtherPanel
类的外部类)。
To start with, the field eyes
is unused therefore unessecary. 要下手,现场
eyes
是不使用的,因此unessecary。 Also, if you want to call the repaint on the whole FollowingEyes
from OtherPanel
, use FollowingEyes.this.repaint()
. 另外,如果你想打电话整个重绘
FollowingEyes
从OtherPanel
,使用FollowingEyes.this.repaint()
What you currently have is repainting only OtherPanel
. 你目前拥有的是仅重绘
OtherPanel
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.