The button in the code below is to me the only object that should listen for ActionEvents but when I resize the window the circle changes color which should only happen when the button is pressed.
Does it in some way use frame.repaint() when resizing the window that generates new values for the drawPanel object or even makes a new drawPanel object for each time the screen is displayed with new random values?
Test.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test implements ActionListener {
JFrame frame;
JButton button;
public static void main (String[] args) {
Test gui = new Test();
gui.go();
}
public void go() {
frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button = new JButton("Pressme!");
button.addActionListener(this);
MyPanelDraw drawPanel = new MyPanelDraw();
frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed (ActionEvent event) {
button.setText("Changed");
frame.repaint();
}
}
MyPanelDraw.java
import javax.swing.*;
import java.awt.*;
class MyPanelDraw extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color startColor = new Color(red, green, blue);
red = (int) (Math.random() * 255);
green = (int) (Math.random() * 255);
blue = (int) (Math.random() * 255);
Color endColor = new Color(red,green, blue);
GradientPaint gradient = new GradientPaint(70,70,startColor, 150,150, endColor);
g2d.setPaint(gradient);
g2d.fillOval(40,70,100,100);
}
}