Skip to content
Advertisement

How do I change the background color of a JFrame dynamically?

I was wondering how would I change this block of code to be able to have a dynamically changing background colour that switches from (red -> black -> green -> black -> blue -> black ->red) and the loop starts again. The background colour should be continuously changing per tick. Right now I have a render method that will continuously run over the loop and I wonder if anyone is able to change is so that it also includes this dynamic colour changing.

private void render() {
        BufferStrategy bs = this.getBufferStrategy();
        if (bs == null) {
            this.createBufferStrategy(3);
            return;
        }

        Graphics g = bs.getDrawGraphics();
        g.setColor(Color.black);
        g.fillRect(0, 0, WIDTH, HEIGHT);


        g.dispose();
        bs.show();
    }

Advertisement

Answer

Hello and welcome to SO!

You are not using swing right. You should be doing all your rendering in paintComponent, which gets automatically called when needed. However paintComponent on JFrame doesn’t do anything, as the JFrame contains a ContentPane (JFrame.getContentPane) and that is the background you want to change. Changing the background of the contentpane should be as simple as

myJFrame.getContentPane().setBackground(newColor);

However not all (J)Components paint their background (JLabel for one), so you may need to create a JPanel and use myJFrame.setContentPane(...); before the code above

Note: To get swing to be single-threaded (as it should be) use SwingUtilities.invokeLater(…) to create/modify Swing classes.

Note 2: Looping in swing should be done using javax.swing.Timer. You don’t need a loop though: Set the new background in your click listener, and then call repaint

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement