Java 单击按钮时如何显示颜色选择器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26565166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:49:30  来源:igfitidea点击:

How to display a color selector when clicking a button?

javabuttoncolorsshapes

提问by Tito

I'm making a program that draws some shapes and fills them with color. I need to change the 'line' color, and want the user to be able to select the color.

我正在制作一个绘制一些形状并用颜色填充它们的程序。我需要更改“线条”颜色,并希望用户能够选择颜色。

How can I, when clicking a button "Choose Color", have a set of colours appear below the button? Is it possible for the selector to be embedded in the UI below the button (and not pop up in a window)?

当单击“选择颜色”按钮时,如何在按钮下方显示一组颜色?是否可以将选择器嵌入到按钮下方的 UI 中(而不是在窗口中弹出)?

I want to display a color selector like in Paint.

我想在 Paint 中显示一个颜色选择器。

采纳答案by luca

Here is a colour selection button class:

这是一个颜色选择按钮类:

  • shows current selected color
  • opens a JColorChooser dialog when pressed
  • fires events when a color is selected
  • 显示当前选择的颜色
  • 按下时打开 JColorChooser 对话框
  • 选择颜色时触发事件

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 ...
    }
});

enter image description here

在此处输入图片说明

    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;
        }
    }

回答by Tom

You can use the JColorChooserlike this:

你可以这样使用JColorChooser

Color newColor = JColorChooser.showDialog(null, "Choose a color", Color.RED);
  • The first argument is the parent java.awt.Componentinstance. Could also be null.
  • The second argument is the title for the dialog.
  • The third argument is the color it should select as default.
  • 第一个参数是父java.awt.Component实例。也可以 null
  • 第二个参数是对话框的标题。
  • 第三个参数是它应该选择的默认颜色。

The dialog returns the selected color if the user presses okor nullif he clicked on cancel.

如果用户按下oknull单击 ,对话框将返回选定的颜色cancel

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

有关更多信息,请参阅此页面:http: //docs.oracle.com/javase/tutorial/uiswing/components/colorchooser.html

Edit: include ColorChooser into existing contentpane

编辑:将 ColorChooser 包含到现有内容窗格中

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.

上面的代码显示了如何创建一个弹出窗口JColorChooser,但也可以将它“包含”到现有的内容窗格中。

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

这是初始化两个组件(JButtonJColorChooser)的代码:

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 toggleColorChoosermethod:

该按钮将立即添加,但颜色选择器尚未添加。它将被添加到toggleColorChooser方法中:

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:

如您所见,您需要一个名为toggled. 只需将其添加为类变量:

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());
}

回答by Daniel Heid

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

我改进了一个 Java Swing 颜色选择器组件,它看起来很漂亮,并允许增强颜色操作:

enter image description here

在此处输入图片说明

Simply add the Maven dependency

只需添加 Maven 依赖项

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

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

到您的项目。现在您可以将 ColorPickerPanel 添加到您的用户界面。