Herseept72 Herseept72 - 7 days ago 5
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 () {}

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

try {
Thread.sleep(100);
frame.getContentPane().setBackground(colours[(int)(Math.random()*(9)+0)]);
}
catch (InterruptedException ex) {

}
}
}
}

Answer

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));
        initComponents();
        add(button);    
    }

    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(){  
            @Override
            public void actionPerformed(ActionEvent e){
                //Change color every (approx) 100 milliseconds
                idx = (idx + 1) % colors.length;   //cycle through the colours
                setBackground(colors[idx]);
            }               
        });    

        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                if(!timer.isRunning())
                    timer.start();
                else
                    timer.stop();   
            }   
        }); 
    }
}

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() {     
            @Override
            public void run() {
                JFrame frame = new JFrame("Rainbow Frame");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new DrawingSpace());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);             
            }
        }); 
    }
}