在JPanel中使用睡眠 [英] Using sleep in JPanel
本文介绍了在JPanel中使用睡眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了一个简单的Java程序(在彼此之间经过一些延迟之后)在屏幕上放置了一些矩形
I wrote a simple java program to place some rectangles on the screen (after some delay between each other)
package guitest2;
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
public void paintComponent( Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 10; i++ ) {
g.drawRect(10+5*i, 10+5*i, 20, 20);
try{
Thread.sleep( 2000 );
}
catch (InterruptedException ex) { }
}
}
}
我在那个班上用过
package guitest2;
import javax.swing.JFrame;
public class Guitest2 {
public static void main(String[] args) {
DrawPanel panel = new DrawPanel();
JFrame app = new JFrame();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
app.add(panel);
app.setSize(450, 250);
app.setVisible(true);
}
}
运行上述代码的问题是,未显示正方形. 10 * 2S = 20秒后,显示的最终面板包含所有正方形.我想要的是:
The problem with running the above code is that, the squares are not shown. After 10*2S = 20 seconds, the final panel is shown containing all squares. What I want are:
1-用g.drawRect
画一个正方形.
1- Draw a square with g.drawRect
.
2-等待2秒
3-删除前一个正方形并绘制一个新正方形.
3- Remove the previous square and draw the new one.
推荐答案
也许您可以使用下面的代码,但我在注释中更改了一些代码.
Maybe you could use the code like below, I changed a bit your code with comments.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.JFrame;
public class RectTest {
DrawPanel panel;
int x;
int y;
public static void main(String[] args) {
new RectTest().startApp();
}
public void startApp() {
panel = new DrawPanel();
JFrame app = new JFrame();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
//modify this line
app.getContentPane().add(panel);
app.setSize(450, 250);
app.setVisible(true);
//added for loop here
for (int i = 0; i < 10; i++ ) {
// x,y here
x = 10+5*i;
y = 10+5*i;
// repaint the panel
panel.repaint();
// wait 2sec
try{
Thread.sleep( 2000 );
}
catch (InterruptedException ex) { }
}
}
class DrawPanel extends JPanel {
public void paintComponent( Graphics g) {
//super.paintComponent(g);
// repaint the backround to see the single reactangles
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.green);
g.drawRect(x, y, 20, 20);
}
}
}
这篇关于在JPanel中使用睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文