Adnan
Adnan

Reputation: 63

Java swing - frequently changing color of the frame

I'm facing the problem with changing the color of the frame. I created timer timer1 and initially set the color of the frame to co1_ for instance (RED). Now, when I tried to compare actual color with predefined values I'm always getting the message:

Frame color is: javax.swing.plaf.ColorUIResource[r=238,g=238,b=238]

and the frame color is still remaining red. Do you have any clue what I'm doing wrong? :)

Thanks in advance.

    Color col1 = Color.RED;
    Color col1_= new Color(255,0,0);
    Color col2 = Color.GREEN;
    Color col2_ = new Color(238,238,238);

    JFrame jfrmForm = new JFrame();
    jfrmForm.setSize(400, 300);
    jfrmForm.setLocation(300,300); 
    jfrmForm.setVisible(rootPaneCheckingEnabled);
    jfrmForm.getContentPane().setBackground(col1_);                      

    //getting color from Frame
    Color c = getContentPane().getBackground();       

    timer.start(); 
    timer.setRepeats(false);

    Timer timer1 = new Timer(1000*frekvCmbBox, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (c.equals(col1_)) {
                jfrmForm.getContentPane().setBackground(col2_);
                System.out.println("Frame color is_: " + c.toString());
            }
            else {
                jfrmForm.getContentPane().setBackground(col1_);
                System.out.println("Frame color is: " + c.toString());
            }                 
        }
    });

    timer1.start();

Upvotes: 1

Views: 805

Answers (3)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

There are many ways of changing the background color or a Swing GUI via animation and two are demonstrated below:

enter image description here

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.event.SwingPropertyChangeSupport;

public class TestColorPanels extends JPanel {
    public static final int PREF_W = 400;
    public static final int PREF_H = 300;

    // constructor
    public TestColorPanels() {
        ColorTimerPanel colorTimerPanel = new ColorTimerPanel();
        ColorSliderPanel colorSliderPanel = new ColorSliderPanel();
        setLayout(new GridLayout(1, 0));
        add(colorTimerPanel);
        add(colorSliderPanel);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            TestColorPanels mainPanel = new TestColorPanels();

            JFrame frame = new JFrame("Color GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}
class ColorTimerPanel extends JPanel {
    public static final int COLOR_COUNT = 400;
    private static final int TIMER_DELAY = 20;
    private static final String STOP = "Stop";
    private static final String START = "Start";
    private List<ColorHue> colorHueList = new ArrayList<>();
    private int colorIndex = 0;
    private JLabel hueValueLabel = new JLabel("000", SwingConstants.CENTER);
    private Timer timer;

    public ColorTimerPanel() {
        JLabel colorHueTextLbl = new JLabel("RGB Color:", SwingConstants.CENTER);
        colorHueTextLbl.setFont(colorHueTextLbl.getFont().deriveFont(24f));
        hueValueLabel.setFont(hueValueLabel.getFont().deriveFont(28f));

        Border innBorder = BorderFactory.createEmptyBorder(15, 15, 15, 15);
        Border outBorder = BorderFactory.createEtchedBorder();
        Border compoundBorder = BorderFactory.createCompoundBorder(outBorder, innBorder);

        JPanel hueValuePanel = new JPanel(new BorderLayout(4, 4));
        hueValuePanel.setBorder(compoundBorder);
        hueValuePanel.setOpaque(false);
        hueValuePanel.add(colorHueTextLbl, BorderLayout.PAGE_START);
        hueValuePanel.add(hueValueLabel, BorderLayout.CENTER);

        JToggleButton toggleButton = new JToggleButton(STOP);
        toggleButton.setMnemonic(KeyEvent.VK_S);
        toggleButton.setFocusPainted(false);
        toggleButton.addItemListener(e -> timerToggled(e));

        setPreferredSize(new Dimension(TestColorPanels.PREF_W, TestColorPanels.PREF_H));
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        add(new JLabel(), gbc); // filler
        gbc.gridy++;
        add(hueValuePanel, gbc);
        gbc.gridy++;
        add(toggleButton, gbc);

        for (int i = 0; i < COLOR_COUNT; i++) {
            float hue = (float) ((i * 1.0) / COLOR_COUNT);
            String text = String.format("%03d", (int) (hue * 100));
            Color color = Color.getHSBColor(hue, 1.0f, 1.0f);
            // rgb text [r, g, b]
            String rgbText = String.format("[%03d, %03d, %03d]", color.getRed(), color.getGreen(), color.getBlue());
            colorHueList.add(new ColorHue(color, rgbText));
        }

        timer = new Timer(TIMER_DELAY, e -> changeColor());
        timer.start();
    }

    private static record ColorHue(Color color, String text) {
    };

    private void changeColor() {
        setBackground(colorHueList.get(colorIndex).color);
        hueValueLabel.setText(colorHueList.get(colorIndex).text);
        colorIndex = (colorIndex + 1) % COLOR_COUNT;
        repaint();
    }

    private void timerToggled(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            timer.stop();
            ((AbstractButton) e.getItem()).setText(START);
        } else {
            timer.start();
            ((AbstractButton) e.getItem()).setText(STOP);
        }
    }
}
class ColorSliderPanel extends JPanel {
    private Map<ColorTitle, ColorSlider> colorSliderMap = Map.of(
        ColorTitle.RED, new ColorSlider(ColorTitle.RED, 0),
        ColorTitle.GREEN, new ColorSlider(ColorTitle.GREEN, 0),
        ColorTitle.BLUE, new ColorSlider(ColorTitle.BLUE, 0)
    );
    private Color backgroundColor = Color.BLACK;

    public ColorSliderPanel() {
        for (ColorSlider colorSlider : colorSliderMap.values()) {
            colorSlider.addPropertyChangeListener(ColorSlider.COLOR_SLIDER, e -> changeColor());
            
        }

        setPreferredSize(new Dimension(TestColorPanels.PREF_W, TestColorPanels.PREF_H));
        setLayout(new GridLayout(1, 0, 10, 0));
        setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        for (ColorTitle colorTitle : ColorTitle.values()) {
            ColorSlider colorSlider = colorSliderMap.get(colorTitle);
            add(colorSlider.getSlider());
        }
        changeColor();
    }

    private void changeColor() {
        int red = colorSliderMap.get(ColorTitle.RED).getValue();
        int green = colorSliderMap.get(ColorTitle.GREEN).getValue();
        int blue = colorSliderMap.get(ColorTitle.BLUE).getValue();
        backgroundColor = new Color(red, green, blue);
        setBackground(backgroundColor);
        repaint();
    }

}
class ColorSlider {
    public static final String COLOR_SLIDER = "Color Slider";
    private SwingPropertyChangeSupport propertyChangeSupport = new SwingPropertyChangeSupport(this);
    private ColorTitle colorTitle;
    private JSlider slider;

    public ColorSlider(ColorTitle colorTitle, int value) {
        this.colorTitle = colorTitle;
        slider = new JSlider(0, 255, value);
        slider.setMajorTickSpacing(50);
        slider.setMinorTickSpacing(10);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.setOpaque(false);
        slider.setBorder(BorderFactory.createTitledBorder(colorTitle.getTitle()));
        slider.setOrientation(SwingConstants.VERTICAL);
        slider.addChangeListener(e -> changeColor());
    }

    public JSlider getSlider() {
        return slider;
    }

    public void changeColor() {
        propertyChangeSupport.firePropertyChange(COLOR_SLIDER, null, this);
    }

    public Color getColor() {
        return colorTitle.getColor();
    }

    public int getValue() {
        return slider.getValue();
    }

    public String getTitle() {
        return colorTitle.getTitle();
    }

    public void setValue(int value) {
        slider.setValue(value);
    }

    public void addPropertyChangeListener(String propertyName, java.beans.PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
    }

}
enum ColorTitle {
    RED("Red", Color.RED), GREEN("Green", Color.GREEN), BLUE("Blue", Color.BLUE);

    private String title;
    private Color color;

    private ColorTitle(String title, Color color) {
        this.title = title;
        this.color = color;
    }

    public String getTitle() {
        return title;
    }

    public Color getColor() {
        return color;
    }
}

Upvotes: 1

c0der
c0der

Reputation: 18792

You can keep track of the color without having to check which color is currently applied to the background:

import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.border.Border;

public class SwingMain {

    private static Color[] colors = {Color.ORANGE, Color.YELLOW, Color.PINK, Color.CYAN};
    private static int counter = 0;
    public static void main(String[] args) {

        JFrame jfrmForm = new JFrame();
        jfrmForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jfrmForm.setLocationRelativeTo(null);
        jfrmForm.getContentPane().setBackground(colors[counter++]);
        //add some content
        JLabel label = new JLabel("Background color chaging test");
        Border padding = BorderFactory.createEmptyBorder(10, 10, 10, 10);
        label.setBorder(padding);
        jfrmForm.add(label);
        jfrmForm.pack();

        Timer timer = new Timer(1000, ae -> {

            jfrmForm.getContentPane().setBackground(colors[counter++]);
            if (counter >= colors.length) {
                counter = 0;
            }
        });

        timer.start();
        jfrmForm.setVisible(true);
    }
}

enter image description here

Upvotes: 1

Adnan
Adnan

Reputation: 63

Andrew, thanks for help - it works now!

Moving Color c = getContentPane().getBackground(); 

to the inside of the action performed method was the key. And, I'm sorry for answering - it seems that I didn't read forum rules carefully.

Upvotes: 1

Related Questions