用Java制作动画
我正在为下周六做一个java作业 它进行得非常顺利,但是我在一个部分中挣扎 这里我想展示一组字符串中的数字,一次一个。 我试着用“Thread.sleep(1000);”来减慢循环的速度 但是,在线程完成之前,不会显示任何内容 下面是图形类中出现问题的部分 有什么我遗漏的吗用Java制作动画,java,for-loop,Java,For Loop,我正在为下周六做一个java作业 它进行得非常顺利,但是我在一个部分中挣扎 这里我想展示一组字符串中的数字,一次一个。 我试着用“Thread.sleep(1000);”来减慢循环的速度 但是,在线程完成之前,不会显示任何内容 下面是图形类中出现问题的部分 有什么我遗漏的吗 public void paint(Graphics g) { setSize(550, 300); //this draws all the random numbers, rev
public void paint(Graphics g)
{
setSize(550, 300);
//this draws all the random numbers, revealing the ans to the user
if (revealNum == 0)
{
g.setColor(Color.BLUE);
g.drawString(randomNumber, 20, 20); //draw String ("the String", x, y)
}
//this reveals the numbers 1 by 1 to the user at the start of the game
if (revealNum==1)
{
for (int x = 0; x < limit; x++)
{
g.setColor(Color.BLUE);
g.drawString(""+x, 20, 20); //draw String ("the String", x, y)
try{
Thread.sleep(1000);
}catch(InterruptedException ex){
System.out.print("Error");
}
repaint();
}
//slow down the loop to show the user
}
public void绘制(图形g)
{
设置大小(550300);
//这将绘制所有随机数,向用户显示ans
如果(revealNum==0)
{
g、 setColor(Color.BLUE);
g、 drawString(randomNumber,20,20);//drawString(“字符串”,x,y)
}
//这将在游戏开始时向用户显示1乘1的数字
如果(revealNum==1)
{
对于(int x=0;x
由于您的应用程序是GUI,因此调用Thread.sleep将使整个应用程序进入睡眠状态。请改用Swing计时器。在计时器的ActionListener中,向显示的字符串添加另一个字母,然后在字符串完成后通过stop()
方法停止计时器
e、 g
而且
- 如果您的是Swing GUI,那么在JLabel或JTextField中显示文本比在GUI上绘制文本更容易
- 如果这是Swing,则不要重写JPanel或JComponent的
方法,而是重写paintComponent(Graphics g)
方法paintComponent(Graphics g)
JLabel l = ...;
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (l.getText().equals("1")) l.setText("2");
else if (l.getText().equals("2)) l.setText("1");
}
});
看看这个问题。
JLabel l = ...;
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (l.getText().equals("1")) l.setText("2");
else if (l.getText().equals("2)) l.setText("1");
}
});