COMP2396
Loading...
Searching...
No Matches
changingoval.java
Go to the documentation of this file.
1import javax.swing.*; // for JFrame, JPanel
2import java.awt.*; // for Color
3import java.awt.event.*; // for MouseListener
4
5public class changingoval {
6 /// random returns a Color object with random values
7 public Color randomColor() {
8 int red = (int) (Math.random() * 255);
9 int green = (int) (Math.random() * 255);
10 int blue = (int) (Math.random() * 255);
11 Color randomColor = new Color(red, green, blue);
12 return randomColor;
13 }
14 int x, y = 70;
15 // required, draw panel is a separate new class to implement
16 class MyDrawPanel extends JPanel {
17 /// need to implement drawing details inside paintComponent()
18 /// as specified in the API
19 public void paintComponent(Graphics g) {
20 // required to call super class paintComponent
21 // to prevent re-drawing the button on the top
22 super.paintComponent(g);
23 // the object g is actually Graphics2D
24 Graphics2D g2d = (Graphics2D) g;
25 // requires Graphics2D object to use GradientPaint
26 // Graphics does not support it
27 g2d.clearRect(0,0, this.getWidth(), this.getHeight());
28 GradientPaint paint = new GradientPaint(70, 70, randomColor(), 150, 150, randomColor());
29 g2d.setPaint(paint);
30 g2d.fillOval(x-70, y-70, 140, 140);
31 }
32 }
33 MyDrawPanel drawPanel = new MyDrawPanel();
34 public static void main(String[] args) {
35 changingoval gui = new changingoval();
36 gui.go();
37 }
38 public void go() {
39 JFrame frame = new JFrame();
40 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
41 frame.add(drawPanel);
42
43 JButton button = new JButton("Change color");
44 frame.add(button, BorderLayout.SOUTH);
45
46 frame.addMouseListener(new clickingListener());
47
48 frame.setSize(300, 300);
49 frame.setVisible(true);
50
51 while (true) {
52 // circle follows the mouse
53 //get the mouse position
54 Point p = frame.getMousePosition();
55 if (p != null) {
56 x = (int) p.getX();
57 y = (int) p.getY();
58 }
59 drawPanel.repaint();
60 try {
61 Thread.sleep(50);
62 } catch (Exception ex) { }
63 }
64 }
65
66 class clickingListener implements MouseListener {
67 public void mousePressed(MouseEvent e) {
68 // panel.repaint() will call paintComponent() again
69 // automatically
70 drawPanel.repaint();
71 }
72 public void mouseReleased(MouseEvent e) {}
73 public void mouseEntered(MouseEvent e) {}
74 public void mouseExited(MouseEvent e) {}
75 public void mouseClicked(MouseEvent e) {}
76 }
77}
void paintComponent(Graphics g)
Color randomColor()
random returns a Color object with random values
static void main(String[] args)