【问题标题】:Updating the position of a rectangle or any other image without overlapping in JPanel更新矩形或任何其他图像的位置而不在 JPanel 中重叠
【发布时间】:2017-08-12 18:40:17
【问题描述】:

我的方法是在循环中使用“reprint()”成功移动图像,这意味着在不重叠的情况下更新其位置,但现在我想看到图像移动,我使用了“thread.sleep()”来给出repaint()s 之间的时间间隔,但它似乎不起作用

import java.awt.*;
import javax.swing.*;

public class jp extends JPanel implements ActionListener{
Timer t;
JPanel jl=new JPanel();
int x,y;
jp(){
    x=10;
    //y=10;
    t=new Timer(5,this);
    t.start();
}
public void actionPerformed(ActionEvent e){
    x++;
    y++;
    if(x>500){
        x=0;
        y=0;
    }
    repaint();
}

public void paintComponent(Graphics g){
    super.paintComponent(g);
    this.setBackground(Color.black);
    g.setColor(Color.blue);
    g.fillRect(x,20,50,50);
}

}

public class Jpanel  extends JFrame{


public static void main(String[] args) {
    jp p=new jp();

    JFrame j=new JFrame("TEST_CASE-1");
    j.add(p);
    j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    j.setSize(700,500);
    j.setVisible(true);
  }

}

【问题讨论】:

  • 1) for(int i=0;i<200;i++){ g.fillRect(25+i,25,50,50); } 这不是制作动画的方式。 2) “我尝试使用 repaint(),但它似乎不起作用” 在上面看到的代码中没有调用 repaint。 3) 将这两个 cmets 绑定在一起,使用基于 Swing 的 Timer 来调整 i 的值,然后调用 repaint。
  • 成功了。但是我怎么能看到图像在移动呢?我尝试使用'Thread.sleep',但它似乎不起作用。我在循环中使用了“repaint()”而不是使用计时器
  • 1) 将当前尝试的minimal reproducible exampleShort, Self Contained, Correct Example 显示为问题的edit。 2) “尝试使用 'Thread.sleep',但它似乎不起作用” 这种方法不需要它(而且很可能会搞砸)。
  • 完成。请立即检查。
  • 你赢了,我用“Thread.sleep()”错了。使用“Swing Timer”后效果很好。感谢您的推动。

标签: java swing


【解决方案1】:

如果您希望通过在paintComponent() 中包含多个绘图来获得动画,例如像您所做的那样使用 for 循环,您将会失望。

它只会执行所有绘图并一次性显示给您。无需同时绘制 200 个矩形,只需绘制 1 个矩形并更新其位置即可。

要执行动画,您需要一个计时器(您可以尝试javax.swing.timer)或者如果您打算做一些更复杂的事情,则需要一个循环。您可以实现无限循环并在循环中执行渲染,同时更新矩形的位置。

最终,无论您采用哪种方法。您将需要存储矩形的位置。以如下方式更新和渲染它:

update position
render
update position
render
update position
render

而不是

update position
update position
update position
render
render
render

带计时器的动画示例: Repainting/refreshing the JFrame

使用循环的动画示例:

while(running){
    update();     //update position of your rect
    repaint();    //redraw your rect (and all other stuff)
}

【讨论】:

  • 它工作了。但是我怎样才能看到图像在移动?我尝试使用“Thread.sleep()”,但它似乎不起作用。我在循环中使用了“repaint()”而不是使用计时器。
  • 您使用 Thread.sleep 以便您的线程可以让其他线程有机会运行。设置较长的睡眠时间会创建较慢的动画。如果动画太快,您可以尝试类似 thread.sleep(10)。当然,10可以换成一个变量来控制帧率。
  • @ryhn 如果此解决方案解决了您的问题,您可以通过单击空心的勾号来接受该解决方案。你得到+2代表作为回报。
  • "Thread.sleep()" 正在工作,但 "reapint()" 方法不起作用。所以它只是增加'i',我只是得到最终位置而不是动画。你能告诉我如何使“repaint()”方法起作用或者我做错了什么吗?
猜你喜欢
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
相关资源
最近更新 更多