/** * The test class ThreadMoveBallInterface. * * @author Gerald Gordon * @version May 28, 2007 */ import java.awt.event.*; import java.awt.*; import javax.swing.*; public class ThreadMoveInterface extends JFrame implements ActionListener,Runnable { private int x,y; private int direction_x,direction_y; private JButton move; private FilledOval redOval; Thread t; private final int FRAME_WIDTH = 300; private final int FRAME_HEIGHT = 300; private final int FRAME_X_AXIS =100; private final int FRAME_Y_AXIS =100; public ThreadMoveInterface() { setSize(FRAME_WIDTH,FRAME_HEIGHT); setLocation(FRAME_X_AXIS,FRAME_Y_AXIS); setTitle("Move Ball"); setLayout(null); move = new JButton("Move"); move.setBounds(100,60,100,30); add(move); move.addActionListener(this); } public void actionPerformed(ActionEvent e) { direction_x = 1;direction_y = 1; x = 20; y = 50; redOval = new FilledOval(x,y,20,20,0); redOval.setForeground(Color.red); this.add(redOval); t = new Thread(this); t.start(); } public void run() { int dx = 15,dy = 15; while(true) { x += dx * direction_x; y += dy * direction_y; if (x >=FRAME_WIDTH -(redOval.getWidth() + dx) || x <= 0) direction_x *= -1; if (y >=FRAME_HEIGHT - (redOval.getHeight()+((double)3/2)*dy) || y <= 0) direction_y *= -1; redOval.setBounds(x,y,20,20); try { Thread.sleep(100); } catch(InterruptedException e) { e.printStackTrace(); } } } }