简体   繁体   中英

How to animate a line in 360 degree like analog clock in java applets

Move a line in 360 degree .

here is my code

import java.applet.*;
import java.awt.*;
import java.util.*;
public class HelloWorldApplet extends Applet implements Runnable{
    Insets insets;
    Thread th;
    int x;
    Image bakground;
    public void paint (Graphics g){
        super.paint(g);
        g.setColor(Color.BLACK);
        g.drawLine(x,10,90,90);
}
public void init() {
    bakground=getImage(getCodeBase(),"clock");
}
@Override
public void start() {
    if(th==null){
        th=new Thread(this);
        th.start();
    }
}
@Override
public void run() {
    // TODO Auto-generated method stub
    for (x = 90;x <=450; x+=5) {
        repaint();
        try{
            th.sleep(100);
        }
        catch(Exception r){

        }
    }
}
}

it rotates but instead of rotating in 360 degree the line become larger and larger. I want to animate the line like an analog Clock.

You can use the magic of math particularly trigonometry to calc the end points of your line being on a circle. But the simplest way would be to use affine transformation. Have a look at this paint() method

public void paint (Graphics g){
    super.paint(g);    
    g.setColor(Color.BLACK);        
    Graphics2D gg = (Graphics2D) g.create();   // create new layer and cast to advanced Graphics2d
    gg.rotate(Math.toRadians(x), 90,90);       // rotate new layer at center position 90,90 around x degrees 
    gg.drawLine(90,90,0,0);                    // draw line to center position
    gg.dispose();                              // push new layer back
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM