Hi there,
I am writing a basic GUI that has a circle in it and when you click the circle it cycles through a choice of 4 colours.
I have written a class that extends JPanel and uses paintComponent to draw the circle, I then use this in another class as an object in a JFrame.
To change the colour of the circle I have used a MouseListener, and a modulus function, however when you click the first time the MouseListener calls the code inside of it once, but the second time it calls the code twice and the third 3 times and so on.
Please help as I can't see why it would do this, below is the code for the JPanel class
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class CircleClicker extends JPanel{ public final static int RED = 1, YELLOW = 2, GREEN = 3, BLUE = 0; int colour = 0; public void paintComponent(Graphics g){ super.paintComponent(g); addMouseListener( new MouseAdapter(){ public void mousePressed(MouseEvent e){ colour = (colour + 1); repaint(); System.out.println("Click value " + colour); } } ); if (colour==RED){ g.setColor(Color.RED); //g.fillOval(100, 100, 50, 50); } else if (colour==YELLOW){ g.setColor(Color.YELLOW); //g.fillOval(100, 100, 50, 50); } else if (colour==GREEN){ g.setColor(Color.GREEN); //g.fillOval(100, 100, 50, 50); } else if (colour==BLUE){ g.setColor(Color.BLUE); //g.fillOval(100, 100, 50, 50); } else{ g.setColor(Color.lightGray); } g.fillOval(0,0,50,50); } public Dimension getPreferredSize(){ return new Dimension(50, 50); } public Dimension getMinimumSize(){ return getPreferredSize(); } }