首页 > 解决方案 > 有没有办法多次执行 paintComponent() 中的代码?

问题描述

我想根据鼠标的 x 和 y 位置在屏幕上移动图像。每次单击鼠标时,图像都应移动到该位置。

public class testSquare {
  public static void main(String[] args) throws Exception {
    //...
    //object that stores x and y of mouse click
    testSquareInfo obj = new testSquareInfo(0, 0);
    //...
    //panel that draws image, seems to only execute once
    JPanel p = new JPanel ()
    {
        protected void paintComponent(Graphics a){ 
            int x = obj.getXPos();
            int y = obj.getYPos(); 
            a.drawImage(img, x, y, 50, 50, null);
        }        
      };
    //listens for mouse click and sends x and y to object
    p.addMouseListener(new MouseAdapter() {
    @Override 
    public void mousePressed(MouseEvent e) {
        int xMouse = e.getX();
        int yMouse = e.getY(); 
        obj.changeX(xMouse);
        obj.changeY(yMouse); 

        System.out.println(xMouse+" "+yMouse);
    }
    }); 

    window.add(p);
    window.setVisible(true); 
  }  
 } 

//Second Class

public class testSquareInfo 
{
    private int x, y; 
    public testSquareInfo(int x, int y)
    {
       this.x = x;
       this.y = y;
    }
    public void changeX(int xNew)
    {
        x = xNew;
    }
    public void changeY(int yNew)
    {
        y = yNew;
    }
    public int getXPos()
    {
        return x;
    }
    public int getYPos()
    {
        return y;
    } 
} 

运行代码时,图像会在窗口的 0, 0, 坐标处绘制,因为 x 和 y 已初始化为这些值。在屏幕上单击不会移动图像,但会正确更新对象中存储的 x 和 y。在测试期间的某一时刻,图像确实移动到了屏幕上的不同位置。然而,这发生在我没有点击窗口的时候,并且从那以后我就无法复制它。我不确定它何时或如何移动。谢谢,

标签: javaswingjpanelpaintcomponentmouselistener

解决方案


p.repaint();在您的mousePressed方法中添加一个。这会导致面板被重绘。

但是,仅这样做只会将另一个 Image 添加到图形组件中。

如果您不想将图像保留在之前的位置,请在方法的开头
添加 a以使面板处于空白状态。super.paintComponent(a);paintComponent

JPanel p = new JPanel() {

    protected void paintComponent(Graphics a){ 

        super.paintComponent(a);

        int x = obj.getXPos();
        int y = obj.getYPos(); 
        a.drawImage(img, x, y, 50, 50, null);
    }        
  };

//listens for mouse click and sends x and y to object
p.addMouseListener(new MouseAdapter() {
    @Override 
    public void mousePressed(MouseEvent e) {
        int xMouse = e.getX();
        int yMouse = e.getY(); 
        obj.changeX(xMouse);
        obj.changeY(yMouse); 

        System.out.println(xMouse+" "+yMouse);
        p.repaint();
    }
}); 

推荐阅读