Jack Garfield
Jack Garfield

Reputation: 9

How to use JColorChooser given Color in other classes?

I have been learning Java just a few weeks so bear that in mind.. I have managed to solve many issues myself until this one:

What I am trying to achieve is using JComponent in a tabbed view so that in one tab you're able to pick a colour (my println shows it actually gets an sRGB value). Then in another class I should be able to get this value and use it in coloring JPanels. Can I just pass the Color object or what is the best way to achieve. What I am trying here is not working too well. Sorry for the messy code - I am a newbie... Here is the main part of the color chooser:

public class Colors extends JPanel implements ChangeListener {

    private JColorChooser jcc = null;
    protected JLabel title;
    static Color newColor;

    public Colors() {
        super(new BorderLayout());

        //Set up the banner at the top of the window
        title = new JLabel();

        //Set up color chooser for setting text color
        jcc = new JColorChooser(title.getForeground());
        jcc.getSelectionModel().addChangeListener(this);
        jcc.setBorder(BorderFactory.createTitledBorder(
                "Choose New Color"));

        AbstractColorChooserPanel[] panels=jcc.getChooserPanels();
        for(AbstractColorChooserPanel p:panels) {
            String displayName = p.getDisplayName();
            switch (displayName) {
                case "HSV":
                    jcc.removeChooserPanel(p);
                    break;
                case "HSL":
                    jcc.removeChooserPanel(p);
                    break;
                case "CMYK":
                    jcc.removeChooserPanel(p);
                    break;
                case "RGB":
                    jcc.removeChooserPanel(p);
                    break;
            }
        }
        add(jcc, BorderLayout.PAGE_END);
    }



    public void stateChanged(ChangeEvent e) {
        Color newColor = jcc.getColor();
        title.setForeground(newColor);
        System.out.println("color = " + newColor);
    }

    public static Color getNewCol() {
        System.out.println("this now =" + newColor);
        return newColor;
    }

    public static Component createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Color Selector");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new Colors();
        return newContentPane;

    }
}

And then I am trying to get hold of the chosen color in the Main.Java class in this way (which is likely wrong). I also note that the value seems to remain always null - probably I am instantiating in a wrong way (value gets lost?)

a.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Click add");
                value++;

                if (value < 21) {


                    JButton jb1 = new JButton();

                    //How to get the COLOR from the JColorChooser class?
                    Color box = Colors.getNewCol();

                    jb1.setBackground(box);
                    jb1.setOpaque(true);

                    //FOR TEST ONLY jb1.setBackground(Color.BLUE);
                    panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
                    panel.add(jb1);
                    panel.setVisible(true);

                    //window.add(paneeli);

                    window.pack();

                    d = new Dimension(700, 500);
                    window.setSize(d);

Probably the answer is too obvious but I just can't see it at the moment.

Upvotes: 1

Views: 862

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

I'd get take your static newColor variable and make it non-static. In my ChangeListener I'd fire the JPanel's innate PropertyChangeSupport so that listeners can be notified. The key is to use an observer design pattern -- For example:

import java.awt.BorderLayout;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.event.*;

@SuppressWarnings("serial")
public class TestColors extends JPanel {
    private JTabbedPane tabbedPane = new JTabbedPane();
    private Colors colors = new Colors();
    private JPanel colorDisplayPanel = new JPanel();

    public TestColors() {
        tabbedPane.add("Colors", colors);
        tabbedPane.add("Color Display", colorDisplayPanel);
        setLayout(new BorderLayout());
        add(tabbedPane);

        // add a PropertyChangeListener to our Colors isntance.
        colors.addPropertyChangeListener(Colors.NEW_COLOR,
                new PropertyChangeListener() {

                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        Color color = (Color) evt.getNewValue();
                        colorDisplayPanel.setBackground(color);
                    }
                });
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("TestColors");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new TestColors());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

@SuppressWarnings("serial")
class Colors extends JPanel implements ChangeListener {
    public static final String NEW_COLOR = "new color";
    private JColorChooser jcc = null;
    protected JLabel title;
    private Color newColor = null;

    public Colors() {
        super(new BorderLayout());

        // Set up the banner at the top of the window
        title = new JLabel("This is my Banner!", SwingConstants.CENTER);

        // Set up color chooser for setting text color
        jcc = new JColorChooser(title.getForeground());
        jcc.getSelectionModel().addChangeListener(this);
        jcc.setBorder(BorderFactory.createTitledBorder("Choose New Color"));

        add(jcc, BorderLayout.CENTER);
        add(title, BorderLayout.PAGE_START);
    }

    public void stateChanged(ChangeEvent e) {
        // Color newColor = jcc.getColor();
        Color oldValue = newColor;
        newColor = jcc.getColor();

        // fire a notification to the Colors JPanel's property change support
        // object. Any listeners will be notified of the color change
        firePropertyChange(NEW_COLOR, oldValue, newColor);
        title.setForeground(newColor);
    }

    public Color getNewCol() {
        System.out.println("this now =" + newColor);
        return newColor;
    }

}

Upvotes: 2

Related Questions