How to display a color selector when clicking a button?

不问归期 提交于 2019-11-29 05:16:43

Here is a colour selection button class:

  • shows current selected color
  • opens a JColorChooser dialog when pressed
  • fires events when a color is selected

Use it in this way:

ColorChooserButton colorChooser = new ColorChooserButton(Color.WHITE);
colorChooser.addColorChangedListener(new ColorChangedListener() {
    @Override
    public void colorChanged(Color newColor) {
            // do something with newColor ...
    }
});

    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.util.ArrayList;
    import java.util.List;

    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JColorChooser;

    public class ColorChooserButton extends JButton {

        private Color current;

        public ColorChooserButton(Color c) {
            setSelectedColor(c); 
            addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    Color newColor = JColorChooser.showDialog(null, "Choose a color", current);
                    setSelectedColor(newColor);
                }
            });
        }

        public Color getSelectedColor() {
            return current;
        }

        public void setSelectedColor(Color newColor) {
            setSelectedColor(newColor, true);
        }

        public void setSelectedColor(Color newColor, boolean notify) {

            if (newColor == null) return;

            current = newColor;
            setIcon(createIcon(current, 16, 16));
            repaint();

            if (notify) {
                // Notify everybody that may be interested.
                for (ColorChangedListener l : listeners) {
                    l.colorChanged(newColor);
                }
            }
        }

        public static interface ColorChangedListener {
            public void colorChanged(Color newColor);
        }

        private List<ColorChangedListener> listeners = new ArrayList<ColorChangedListener>();

        public void addColorChangedListener(ColorChangedListener toAdd) {
            listeners.add(toAdd);
        }

        public static  ImageIcon createIcon(Color main, int width, int height) {
            BufferedImage image = new BufferedImage(width, height, java.awt.image.BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = image.createGraphics();
            graphics.setColor(main);
            graphics.fillRect(0, 0, width, height);
            graphics.setXORMode(Color.DARK_GRAY);
            graphics.drawRect(0, 0, width-1, height-1);
            image.flush();
            ImageIcon icon = new ImageIcon(image);
            return icon;
        }
    }

You can use the JColorChooser like this:

Color newColor = JColorChooser.showDialog(null, "Choose a color", Color.RED);
  • The first argument is the parent java.awt.Component instance. Could also be null.
  • The second argument is the title for the dialog.
  • The third argument is the color it should select as default.

The dialog returns the selected color if the user presses ok or null if he clicked on cancel.

See this page for more information: http://docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html.

Edit: include ColorChooser into existing contentpane

The above code shows how to create a pop up with for the JColorChooser, but it is also possible to "include" it into the existing contentpane.

This is the code to initialize both components (JButton and JColorChooser):

button = new JButton("Choose color");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        toggleColorChooser(); // show and hide the color chooser
    }
});
button.setBounds(10, 11, 150, 23);
contentPane.add(button);

colorChooser = new JColorChooser(Color.BLACK); // default color is black
colorChooser.setBorder(null);
colorChooser.getSelectionModel().addChangeListener(new ChangeListener() {
    public void stateChanged(ChangeEvent e) {
        colorChanged(); // change background color of "button"
    }
});

The button will be added immediately, but the color chooser not yet. It will be added in the toggleColorChooser method:

protected void toggleColorChooser() {
    if (toggled) {
        contentPane.remove(colorChooser);
    } else {
        colorChooser.setBounds(button.getX(), button.getY() + 20, 600, 300);
        colorChooser.setVisible(true);
        contentPane.add(colorChooser);
    }
    toggled = !toggled;
    contentPane.validate();
    contentPane.repaint();
}

The color chooser will be added to the panel beneath the button. You may change the bounds if you have a different layout or if you're using a layout manager.

As you can see, you'll need a variable called toggled. Just add it as class variable:

private boolean toggled = false;

The last method will be called it the user selects a color on the color chooser. It will change the background color of the button:

protected void colorChanged() {
    button.setBackground(colorChooser.getSelectionModel().getSelectedColor());
}

I improved a Java Swing Color Picker component that looks beautiful and allows enhanced color manipulation:

Simply add the Maven dependency

<dependency>
  <groupId>org.drjekyll</groupId>
  <artifactId>colorpicker</artifactId>
  <version>1.3</version>
</dependency>

to your project. Now you can add the ColorPickerPanel to your user interface.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!