I am trying to create a flashing circle. I have got to the point where it changed once and then it throws and error Exception in thread "AWT-EventQueue-0
i have no idea why. can you help me? This is my code:
public class Final {
private static JPanel contentPane;
private static int cnt = 0;
private static int counter =0;
private static Color[] colours = {
Color.ORANGE,
Color.GRAY
};
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setSize(400, 525);
frame.setLocationByPlatform(true);
frame.setVisible(true);
ActionListener actListner = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (cnt == (colours.length)) {
cnt = 0;
}
frame.setBackground(colours[cnt++]);
counter = cnt;
System.out.println("Counter = "+cnt);
}
};
contentPane = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(colours[counter]);
g.fillOval(160, 70, 50, 50);
}
};
frame.add(contentPane);
Timer timer = new Timer(500, actListner);
timer.start();
}
}
The full exception:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2
at Final$2.paintComponent(Final.java:56)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent._paintImmediately(Unknown Source)
at javax.swing.JComponent.paintImmediately(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at javax.swing.RepaintManager$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$1300(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)