简体   繁体   中英

Change a JPanel color using the JColorChooser

Im trying to change the color of a JPanel using the JColorChooser when the "apply" button is pressed, but i'm not sure how to actually make the color change. How would I do that?

private class SetColorAction implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
       setColor(DrawnView.colorChooser.getColor());
       //Color color;

    }

}

^ is one in class while the stuff below is in a different one

public void setColor(Color color){
    this.setBackground(color);


}
public ViewUserActions() {

    this.applyColorBtn.setVisible(false);
    this.discardChangesBtn.setVisible(false);

    this.editBtn.addActionListener((ActionEvent ae) -> {
        if (this.editBtn.isSelected()) {

            this.applyColorBtn.setVisible(true);
            this.discardChangesBtn.setVisible(true);
        } else {

            this.applyColorBtn.setVisible(false);
            this.discardChangesBtn.setVisible(false);
        }
    });



    this.applyColorBtn.addActionListener(new SetColorAction());
    this.discardChangesBtn.addActionListener(new SetColorAction());
    this.applyColorBtn.addActionListener(new GetInfoAction());
    this.discardChangesBtn.addActionListener(new GetInfoAction());


}

Here is a short demo of changing the background color of a JPanel by a button click.
This cam also give you an idea of mcve , doing just that and nothing more:

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Frame extends JFrame {

    JPanel panel;
    Color[] colors = new Color[] {Color.YELLOW, Color.CYAN, Color.LIGHT_GRAY, Color.WHITE};
    int counter =0;

    Frame() {

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        JButton button = new JButton("Change color");
        button.addActionListener( ae -> setColor());
        add(button, BorderLayout.NORTH);

        panel = new JPanel();
        panel.add(new JLabel ("Test panel"));
        add(panel, BorderLayout.CENTER);

        pack();
        setVisible(true);
    }

    private void setColor() {
        panel.setBackground(colors[counter++]);
        counter = (counter >= colors.length) ?  0 : counter;
    }

    public static void main(String[] args)  {
        new Frame();
    }
}

Try this simple source code:

颜色选择器

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ColorChooserExample {

    private static JFrame frame;

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

    private static void runColorChangerApp() {
        frame = new JFrame();
        frame.setTitle("JPanel Color Changer");
        frame.getContentPane().setLayout(new GridLayout(1, 1));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(400, 250, 400, 300);

        frame.getContentPane().add(getHomePanel());

        frame.setVisible(true);
    }

    private static JPanel getHomePanel() {
        final JPanel panel = new JPanel();
        panel.setOpaque(true);

        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                //Fire on Mouse Right Click
                if(evt.getButton() == MouseEvent.BUTTON3) {
                    frame.setTitle("Listened Right Click");
                    Color initColor = panel.getBackground();
                    Color choosedColor = JColorChooser.showDialog(panel, 
                            "Choose JPanel Background Color", initColor);
                    frame.setTitle("JPanel Color Changer");
                    panel.setBackground(choosedColor);
                }
            }
        });
        return panel;
    }

}

I am going to assume by the "apply" button, you mean the "ok" button of the JColorChooser dialog. In that case, here is an optimal solution:

Color r = JColorChooser.showDialog(null, "Select Color for JPanel", Color.CYAN);
//null is the parent Component for the dialog,The String is the title, and cyan 
//will be the initially selected Color.
if(r==null)
    { //perform whatever you would do if the user cancels the dialog }
else
    { jpanelobj.setBackground(r); }

This should do the trick, but here's my advice for you. JColorChooser extends JComponent, and this means that IT CAN BE ADDED AS A COMPONENT to a Frame, giving you control such as adding ChangeListeners to instantaneously detect a Color change. Another method you may find helpful is:

    JDialog jd=JColorChooser.createDialog(Component c, 
                                          String title, 
                                          boolean modal, 
                                          JColorChooser chooserPane, 
                                          ActionListener okListener, 
                                          ActionListener cancelListener);
                                          

Where c is the parent component-leave it null, usually.
The title is the dialogs Title modal is a boolean value which specifies whether you want the program to wait for the the dialog to be responded to by the user before continuing the program thread execution.

chooserPane is the JColorChooser you want as the main chooser->eg:

new JColorChooser(Color.GREEN);

okListener and cancelListener are action listeners for ok and cancel buttons. This method gives you control over the dialogs buttons, display, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM