Using threads for animation in a non-main class.
I am trying to create an abstract class that will control any JComponent with the arrow keys when extended, but I don't know how. Right now, I havent added a KeyAdapter for the arrow keys, but I have added a run method that calls another method called "move" which is supposed to print the word "hello" in the output every 33 milliseconds. Once I quit the application, all of the "hello"s hit me at once, but they are not timed. Here is my code so far.
Main Class:
Code:
package shoot;
import javax.swing.JFrame;
class Main extends Thread{
JFrame frame = new JFrame("Shooter");
public static void main(String[] args){
Main main = new Main();
main.init();
}
private void init(){
Thread thread = new Thread(this);
thread.start();
Ship ship = new Ship();
frame.setVisible(true);
frame.setSize(500, 500);
frame.getContentPane().add(ship);
ship.run();
}
}
Ship Class:
Code:
package shoot;
import java.awt.Graphics;
public class Ship extends Controllable{
@Override public void paintComponent(Graphics g){
g.fillRect(20, 0, 10, 10);
g.fillRect(0, 10, 50, 30);
repaint();
}
@Override
public void move() {
System.out.print("hello");
}
}
Controllable Class:
Code:
package shoot;
import java.awt.Graphics;
import javax.swing.JPanel;
public abstract class Controllable extends JPanel implements Runnable{
int sleepTime = 33;
public Controllable(){
}
@Override public void run() {
while(true){
try {
move();
Thread.sleep(33);
} catch (InterruptedException ex) {
System.out.print("Thread in class Controls Interrupted \n at line 17");
}
}
}
public abstract void move();
public int getSleepTime(){
return sleepTime;
}
@Override public abstract void paintComponent(Graphics g);
}
Any ideas?
Re: Using threads for animation in a non-main class.
Re: Using threads for animation in a non-main class.
Moved from 'New to Java'
db
Re: Using threads for animation in a non-main class.
Quote:
Originally Posted by
camickr
Thanks, but that leaves me with another question. What are threads used for?
Re: Using threads for animation in a non-main class.
You use a Thread to execute long running tasks so you don't block the Swing GUI from repainting itself. Read the section from the above tutorial on "Concurrency" which explains more about threads.