在Java中的动画上使用线程 [英] Using threads on animations in Java

查看:132
本文介绍了在Java中的动画上使用线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个具有两个形状的类,即两个椭圆形.我在这里画它们.

I have created a class whit two shapes namely two ovals. Here I draw them.

import ...;

public class Drawings extends JPanel{
    public double degrees = 0;

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        int xcen =  getWidth() / 2;
        int ycen =  getHeight()/ 2;

        int radius = 10;
        degrees++;

        double radians = Math.toRadians(degrees);
        int posx = (int)(100.getDistance() * Math.cos(radians));
        int posy = (int)(100.getDistance() * Math.sin(radians));

        g.setColor(Color.BLUE);
        g.FillOval(xcen + posx, ycen + posy, 20, 20);

        g.setColor(Color.GREEN);
        g.drawOval(xcen + posx, ycen + posy, 100,100)

   }
} 

现在,我在主要环境中实现它.

Now I implement it in a main.

import ....;

public class Animate extends JFrame{
  public static void main(String [] args)
  {

   JFrame window = new JFrame();
   window.add(new Drawings());
   window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   window.setSize(500,500);
   window.setLocationRelativeTo(null); 
   window.setVisible(true);

   //now I implement the thread to animate the two shapes
   Thread paintThread = new Thread(new Runnable(){
   @Override
        public void run(){
              while(true)
              {
                   window.repaint();
                   try{
                        Thread.sleep(25);//determines how slow the ovals will move
                   }catch(InterruptedException e){
                       e.printStackTrace();
                   }
                 }
               }
             });

              paintThread.start();//start the animation

            }  
         }

程序运行时,两个椭圆形在屏幕上旋转.但是,两个椭圆形的旋转速度与我预期的相同,但我希望两个椭圆形以不同的速度移动.

When the program runs the two Ovals rotate on the screen. But the two ovals rotates at the same speed as I would expect but I would like the two ovals to move at diffident speeds.

我尝试使用一种方法以不同的速度移动它们,但没有成功. 我将如何使两个椭圆形以不同的速度运动?

I have tried using a method to move them at different speed but with no success. How would I get the two ovals moving at different speeds?

推荐答案

使一个类代表一个椭圆.进行两个实例.给两个实例不同的角速度.当前,因为每25毫秒将度数增加1.0,所以角速度固定为每秒40度.如果每个椭圆都有其自己的度数字段,并且将两个椭圆增加不同的数量,则椭圆将以不同的速率旋转.

Make a class to represent an oval. Make two instances. Give the two instances different angular velocities. Currently because you increment degrees by 1.0 every 25 ms you have an angular velocity fixed at 40 degrees per second. If each oval has its own degrees field and you increment the two by different amounts, the ovals will rotate at different rates.

这篇关于在Java中的动画上使用线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆