java - 尝试使图像随机移动但它没有移动

标签 java

我试图让图像随机移动,但由于某种原因它不起作用。图像出现在面板中,但没有移动。我为此使用了两个类:一个主类和一个子类。这是我的子类的代码。

public Image()
{

    randomPosition();

    try {
    image = ImageIO.read(new File("image.png"));

    } catch (IOException e) {}


}


public void paint(Graphics g)
{
    g.drawImage(image, x, y, this);
    Toolkit.getDefaultToolkit().sync();
    g.dispose();    
}



public void move()
{


    x += dx;
    y += dy;


    if (x >= 550) {
        x = 550;
        randomDirection();
      }
      if (x <= 1) {
        x = 1;
        randomDirection();
      }
      if (y >= 350) {
        y = 350;
        randomDirection();
      }
      if (y <= 1) {
        y = 1;
        randomDirection();
      }
}

public void randomDirection() {
    double speed = 2.0;
    double direction = Math.random()*2*Math.PI;
    dx = (int) (speed * Math.cos(direction));
    dy = (int) (speed * Math.sin(direction));
    }


public void randomPosition()
{
    x = LEFT_WALL + (int) (Math.random() * (RIGHT_WALL - LEFT_WALL));
    y = UP_WALL + (int) (Math.random() * (DOWN_WALL - UP_WALL));
}

public void run()
{

    long beforeTime, timeDiff, sleep;
    beforeTime = System.currentTimeMillis();
    while (true)
    {
        move();
        repaint();

        timeDiff = System.currentTimeMillis() - beforeTime;
        sleep = DELAY - timeDiff;

        if (sleep > 2)
        {
            sleep = 1;
        }
        try
        {
            Thread.sleep(sleep);
        }
        catch (InterruptedException e)
        {
            System.out.println("interrupted");
        }

        beforeTime = System.currentTimeMillis();
    }
}

这是我启动线程的主类:

public void addImage(){
            Image I = new Image();
            x = panel.getGraphics();
            I.paint(x);
            Thread thr=new Thread(I);
            thr.start();
        }

最佳答案

  • paint() 应该是

像这样:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    ...
}
  • 切勿直接调用paint()/paintComponent()。而是调用 repaint(),这会将其添加到事件队列中。图形对象由swing传递。

  • 我不确定 g.dispose() 是否必要,并且可能会导致问题。

  • 检查您的绘画所在的面板尺寸是否正确 - 调试此问题的快速方法是 panel.setBorder(BorderFactory.createLineBorder(Color.RED));
  • 考虑使用 javax.swing.Timer 而不是线程。这不是问题的原因,但会更干净。

关于java - 尝试使图像随机移动但它没有移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28997654/

相关文章:

java - 同步是否适用于引用/指针变量?

java - 如何在 Java 中按部分加载序列化对象

java - 如何在 map 中使用通用类型?

java - 自动调整字体大小

java - Liferay 6.2 部署失败,缺少/不可用的 JBoss 依赖项

java - String.getBytes() 的结果是否会包含零?

java - 格式错误的 JSON : Unexpected '<' in Spring

java - Libgdx chainshape 位置

java - 在 JProfiler 中显示监视器堆栈跟踪中的行号

java - 是否有返回请求的 Number 子类的 Java 数字字符串文字的解析器?