【问题标题】:Why isn't my java animation working?为什么我的 java 动画不起作用?
【发布时间】:2013-03-29 06:26:22
【问题描述】:

当我想让雨滴顺着屏幕向下移动直到它们落到底部然后再做一次时,一切都静止了。我使用了可运行的实现,并有一个重新绘制它的运行方法。有人知道我错过了什么吗?

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

public class Screensaver extends JPanel implements Runnable{
    private final static int FRAME_HEIGHT = 600;
    private final static int FRAME_WIDTH = 600;
    int rainY = 100;
    int rainGo = 1;
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
        frame.add(new Screensaver());
        frame.setVisible(true);

    }
    public Screensaver(){
        Color background;
        background = new Color(212,202,115);
        setBackground(background);
    }
     protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Color tree;
            Color leaves;
            Color cloud;
            Color rain;
            rain = new Color(0,128,255);
            cloud = new Color(160,160,160);
            leaves = new Color(0,204,0);
            tree = new Color(102,0,0);

            g.setColor(tree);
            //g.drawLine(400, 375, 360, 340);
            g.fillRect(400, 250,80, 320 );
            g.setColor(leaves);
            g.fillOval(340,150 , 200, 160);
            g.setColor(cloud);
            g.fillOval(10,5,550,100);

            Random random = new Random();
            int rainX1 = random.nextInt(500) + 40;
            int rainW1 = random.nextInt(30) + 10;
            int rainX2 = random.nextInt(500) + 40;
            int rainW2 = random.nextInt(30) + 10;
            int rainX3 = random.nextInt(500) + 40;
            int rainW3 = random.nextInt(30) + 10;
            int rainX4 = random.nextInt(500) + 40;
            int rainW4 = random.nextInt(30) + 10;

            g.setColor(rain);
            g.fillOval(rainX1, rainY + rainGo, rainW1, rainW1);
            g.fillOval(rainX2, rainY+ rainGo, rainW2, rainW2);
            g.fillOval(rainX3, rainY+ rainGo, rainW3, rainW3);
            g.fillOval(rainX4, rainY+ rainGo, rainW4, rainW4);


        }
     public void run(){
         while(true){
             changeRain();
             repaint();
         }
     }
     public void changeRain(){
         if(rainY+rainGo< FRAME_HEIGHT){
             rainGo++;
         }
         else{
             rainGo = 1;
         }
     }
}

【问题讨论】:

  • 在哪里创建后台线程并启动它?
  • 你的run方法是如何执行的?

标签: java swing animation graphics colors


【解决方案1】:

简短回答:您没有启动 Thread 来启动动画。

完整答案:使用 Swings 并发机制之一,例如用于动画的 Swing Timer。 Swing 计时器旨在与 Swing 组件正确交互。

【讨论】:

    【解决方案2】:

    我在您的代码中没有看到您创建后台线程并启动它的任何地方。线程不只是自己开始。如果您确实走这条路,请考虑在您的 run 方法中放置一个 Thread.sleep(...) 以使 while 循环稍微暂停一下。最好为动画使用 Swing Timer。

    【讨论】:

      猜你喜欢
      • 2017-08-29
      • 2019-07-09
      • 2015-09-22
      • 2016-02-29
      • 1970-01-01
      • 2020-10-03
      • 2016-08-01
      • 2013-02-02
      相关资源
      最近更新 更多