So I have created a GUI in which a user clicks a JButton to change the color of a circle... I have used the paintComponent method which I am aware will be called when the GUI is displayed and when the GUI window is minimised and then re-opened.
However when I maximise my window on mac the paintComponent method is called several times and the circle cycles through many different colours, why does this occur, as in why is the paintComponent method called multiple times.
Source Code:
GUI Class
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Gui extends JFrame {
JPanel row1 = new JPanel();
JPanel drawingSpace = new MyDrawPanel();
JButton colourChange = new JButton("Click here to change colors");
public Gui(){
setTitle("Circle Colors");
setSize(400,650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout layoutMaster = new BorderLayout();
colourChange.addActionListener(new EventHandler(this));
setLayout(layoutMaster);
setLayout(layoutMaster);
row1.add(colourChange);
add(drawingSpace, BorderLayout.CENTER);
add(row1, BorderLayout.SOUTH);
setVisible(true);
}
public static void main(String[] args){
Gui createPage = new Gui();
}
}
EVENT HANDLING Class
import java.awt.event.*;
import java.awt.*;
public class EventHandler implements ActionListener {
Gui refRemote;
public EventHandler(Gui obj){
refRemote = obj;
}
public void actionPerformed(ActionEvent e1){
String buttonTitle = e1.getActionCommand();
if(buttonTitle.equals("Click here to change colors"))
{
refRemote.repaint();
}
}
}
DRAWING PANEL Class
import javax.swing.*;
import java.awt.*;
public class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g1){
Graphics2D g2D = (Graphics2D) g1;
int red = (int) (Math.random()*256);
int green = (int) (Math.random()*256);
int blue = (int) (Math.random()*256);
Color initialColor = new Color(red, green, blue);
red = (int) (Math.random()*256);
green = (int) (Math.random()*256);
blue = (int) (Math.random()*256);
Color finalColor = new Color(red, green, blue);
///GradientPaint gradient = new GradientPaint(50, 50, initialColor, 100, 100, finalColor);
g2D.setPaint(initialColor);
g2D.fillOval(100, 150, 200, 200);
}
}
Instead of changing the colour on repaint, have a specific method to change the colour that will be called from the ActionListener
. When paintComponent
is called it should then just use whatever the current colour is.