Home > Blockchain >  Changing JFrame's background color back to default
Changing JFrame's background color back to default

Time:12-26

Is there a way to clear a JFrame's background color or at least change it back to the default one?

CodePudding user response:

Swing using internally a concept called ColorUIResource, usually means the color defined and used by the framework.

One important thinks that I learned, is that the Swing will not change the color of the component if the color is not a specific instance of ColorUIResource.

If you want to restore the color of your JFrame, you could do something similar

frame.setBackground(new ColorUIResource(Color.white));

and to restore the original color of your component you can a single call

SwingUtilities.updateComponentTreeUI(window)

CodePudding user response:

JFrame is a top-level container, hence I think you are referring to the background color of its content pane which, by default, is a JPanel.

The default background color depends on the look-and-feel and can be obtained via class javax.swing.UIManager.

Here is a very basic application demonstrating. I explicitly set the content pane background to yellow and after clicking on the button, the background reverts to its default value.

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;

public class FrameTst {
    private static ColorUIResource  bg;
    private JFrame  frame;

    private void createAndDisplayGui() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel contentPane =  (JPanel) frame.getContentPane();
        contentPane.setBackground(Color.yellow);
        contentPane.setBorder(BorderFactory.createLineBorder(Color.red, 2));
        contentPane.setLayout(new FlowLayout(FlowLayout.LEADING));
        JButton button = new JButton("Button");
        button.addActionListener(event -> contentPane.setBackground(bg));
        contentPane.add(button);
        frame.setSize(450, 350);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        bg = (ColorUIResource) UIManager.get("Panel.background");
        EventQueue.invokeLater(() -> new FrameTst().createAndDisplayGui());
    }
}
  • Related