Priya
Posts: 2
Nickname: sutha
Registered: Apr, 2003
Urgent Problem on GUI
Posted: Apr 12, 2003 3:11 AM
Advertisement
I need to write a program whereby, a ball of radius 40 is moved randomly within a red circle of framesize (300,300) when a button is clicked. However, i can only manage the ball to move all around the frame, how can i ge it to move within the red circle only? Any help would be greatly appreciated! Thanks! Im a beginner so detailed explanations would be better. Thanks again. import java.awt.*; import java.awt.event.*; import javax.swing.*; class Lab_06 extends JFrame { public Lab_06(String name) { super(name); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); getContentPane().add(new Circle(300, 300)); RandomBall display = new RandomBall(300, 300); display.setBackground(Color.yellow); contentPane.add(display, BorderLayout.CENTER); JPanel control = new JPanel(new FlowLayout()); control.setBackground(Color.orange); contentPane.add(control, BorderLayout.SOUTH); JButton button = new JButton("Move"); control.add(button); button.addActionListener(display); setDe faultCloseOperation(EXIT_ON_CLOSE); pack(); setResizable(false); setVisible(true ); } public static void main(String[] args) { JFrame f = new Lab_06("Random Ball Generator"); } } class Circle extends JLabel { public Circle(int width, int height) { setPreferredSize(new Dimension(width, height)); } } class RandomBall extends JLabel implements ActionListener { private int x0, y0, wBall, hBall, distance; public RandomBall(int width, int height) { setPreferredSize(new Dimension(width, height)); setOpaque(true); } protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.blue); g.fillOval(x0, y0, wBall, hBall); int x = getWidth(), y = getHeight(); g.setColor(Color.RED); g.drawOval(x/300, y/300, x, y); } public void actionPerformed(ActionEvent e) { x0 = (int)(wLabel*Math.random()); y0 = (int)(hLabel*Math.random()); wBall = 40; hBall = 40; repaint(); } }