Herseept72 Herseept72 - 1 year ago 57
Java Question

I Have A Random Colour Program And I Need It To Rapidly Switch Through Colours

I have an ActionListener for my 'Aneurysm Mode' Button but when I press it, it does nothing...

Here is the code for the ActionListener:

private class AneurysmMode implements ActionListener {

AneurysmMode () {}

public void actionPerformed(ActionEvent e) {
while (true) {

try {
catch (InterruptedException ex) {


Answer Source

enter image description here

Unless you are making something sophisticated such as a game where you need much control over all the rendering. If not, you can make full use of javax.swing.timer instead of implementing your own rendering loop.

You should not apply the rendering loop or sleep in the EDT. The actions within actionPerformed is usually a "one-time" action.

Your actionPerformed in the button in this case works just like an "on/off" button, hence all you need to do is to turn on/off the timer (which controls the animation) when it is clicked:

class DrawingSpace extends JPanel{

    private JButton button;
    private Timer timer;
    private int idx;
    private Color[] colors;    

    public DrawingSpace(){
        setPreferredSize(new Dimension(200, 200));

    public void initComponents(){
        idx = 0;
        colors = new Color[]{Color.RED, Color.YELLOW, Color.ORANGE, Color.MAGENTA, Color.BLUE, Color.CYAN, Color.GREEN};
        button = new JButton("Let the colors rock!");
        timer = new Timer(100, new ActionListener(){  
            public void actionPerformed(ActionEvent e){
                //Change color every (approx) 100 milliseconds
                idx = (idx + 1) % colors.length;   //cycle through the colours

        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){

A runner class to run the code:

class RainbowRunner{
    public static void main(String[] args){     
        // Run the GUI code on the EDT
        SwingUtilities.invokeLater(new Runnable() {     
            public void run() {
                JFrame frame = new JFrame("Rainbow Frame");
                frame.add(new DrawingSpace());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download