Hi,
Following is the code I came up with, I get the feeling I over-complicated the program, please point me in the right direction, TIA.
D.Code:import java.awt.*; import javax.swing.*; class BouncingDisplay extends JFrame { public static void main(String[] arguments) { BouncingDisplay bd = new BouncingDisplay(); } public BouncingDisplay() { super("Bouncing Display"); setSize(400, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); BouncingPanel bp = new BouncingPanel(); getContentPane().add(bp); setVisible(true); } } class BouncingPanel extends JPanel implements Runnable { Thread runner; int x; int y; public BouncingPanel() { setSize(200, 200); Thread runner = new Thread(this); runner.start(); } public void run() { char x_dir = '+'; char y_dir = '+'; while(true) { if(x_dir == '+') { if(x > getSize().width - 10) { x_dir = '-'; x -= 4; } else { x += 4; } } else { if(x <= 0) { x_dir = '+'; x += 4; } else { x -= 4; } } if(y_dir == '+') { if(y > getSize().height - 10) { y_dir = '-'; y -= 4; } else { y += 4; } } else { if(y <= 0) { y_dir = '+'; y += 4; } else { y -= 4; } } repaint(); try { Thread.sleep(100); } catch (InterruptedException e) { } } } public void paintComponent(Graphics canvas) { Graphics2D canvas2D = (Graphics2D)canvas; canvas2D.clearRect(0, 0, getSize().width, getSize().height); canvas2D.setColor(Color.blue); canvas2D.fillRect(x, y, 10, 10); } }




Reply With Quote