📜  Java摇摆 | JColorChooser 类

📅  最后修改于: 2022-05-13 01:55:16.156000             🧑  作者: Mango

Java摇摆 | JColorChooser 类

JColorChooser 提供了一个控件窗格,旨在允许用户操作和选择颜色。此类提供三个级别的 API

  1. 显示模式颜色选择器对话框并返回用户选择的颜色的静态便捷方法。
  2. 一种用于创建颜色选择器对话框的静态便捷方法,其中可以指定ActionListener在用户按下其中一个对话框按钮时调用。
  3. 直接(在任何容器内)创建JColorChooser窗格实例的能力。可以添加PropertyChange侦听器来检测当前“颜色”属性何时发生变化。

类的构造函数:

  1. JColorChooser():创建一个初始颜色为白色的颜色选择器窗格。
  2. JColorChooser(Color initialColor):使用指定的初始颜色创建颜色选择器窗格。
  3. JColorChooser(ColorSelectionModel model):使用指定的ColorSelectionModel创建颜色选择器窗格。

常用方法:

MethodDescription
setColor(Color color)Sets the current color of the color chooser to the specified color.
setColor(int c)Sets the current color of the color chooser to the specified color.
setColor(int r, int g, int b)Sets the current color of the color chooser to the specified RGB color.
showDialog(Component cmp, String title, Color init_Color)Shows a modal color-chooser dialog and blocks until the dialog is hidden.
updateUI()Notification from the UIManager that the L&F has changed 
 
setChooserPanels(AbstractColorChooserPanel[] panels)Specifies the Color Panels used to choose a color value.
addChooserPanel(AbstractColorChooserPanel panel)Adds a color chooser panel to the color chooser.
setUI(ColorChooserUI ui)Sets the L&F object that renders this component.
setSelectionModel(ColorSelectionModel newModel)Sets the model containing the selected color.
setPreviewPanel(JComponent preview)Sets the current preview panel.

创建自定义选择器面板:默认颜色选择器提供五个选择器面板:

  1. 色板:用于从色板集合中选择一种颜色。
  2. HSV:用于使用 Hue-Saturation-Value 颜色表示来选择颜色。在 JDK 7 之前,它被称为 HSB,代表色相饱和度。
  3. HSL:用于使用色调-饱和度-亮度颜色表示来选择颜色。
  4. RGB:用于使用红-绿-蓝颜色模型选择颜色。
  5. CMYK:用于使用原色或四色模型选择颜色。

下面的程序说明了 JColorChooser 类的使用:

1. 使用 ChangeListener 实现 JColorChooser 类的Java程序:在这个程序中,我们首先在窗口顶部创建一个标签,其中显示一些文本,我们将在其中应用颜色更改。设置前景色和背景色。设置字体的大小和类型。创建一个面板并设置其布局。现在设置颜色选择器以设置文本颜色。使用stateChanged()方法,使用getColor()方法生成文本颜色更改的事件。现在创建 GUI,创建一个设置窗口。设置窗口的默认关闭操作。创建和设置内容窗格并将内容添加到框架并显示窗口。

Java
// Java program to implement JColorChooser
// class using ChangeListener
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;
 
public class ColorChooserDemo extends JPanel
 
    implements ChangeListener {
 
    protected JColorChooser Jcc;
    protected JLabel label;
 
    public ColorChooserDemo()
    {
        super(new BorderLayout());
 
        // Set up the Label at the top of the window
        label = new JLabel("Welcome to GeeksforGeeks",
                                       JLabel.CENTER);
 
        // set the foreground color of the text
        label.setForeground(Color.green);
 
        // set background color of the field
        label.setBackground(Color.WHITE);
        label.setOpaque(true);
 
        // set font type and size of the text
        label.setFont(new Font("SansSerif", Font.BOLD, 30));
 
        // set size of the label
        label.setPreferredSize(new Dimension(100, 65));
 
        // create a Panel and set its layout
        JPanel bannerPanel = new JPanel(new BorderLayout());
        bannerPanel.add(label, BorderLayout.CENTER);
        bannerPanel.setBorder(BorderFactory.createTitledBorder("Label"));
 
        // Set up color chooser for setting text color
        Jcc = new JColorChooser(label.getForeground());
        Jcc.getSelectionModel().addChangeListener(this);
        Jcc.setBorder(BorderFactory.createTitledBorder(
            "Choose Text Color"));
 
        add(bannerPanel, BorderLayout.CENTER);
        add(Jcc, BorderLayout.PAGE_END);
    }
 
    public void stateChanged(ChangeEvent e)
    {
        Color newColor = Jcc.getColor();
        label.setForeground(newColor);
    }
 
    // Create the GUI and show it.  For thread safety,
    // this method should be invoked from the
    // event-dispatching thread.
    private static void createAndShowGUI()
    {
 
        // Create and set up the window.
        JFrame frame = new JFrame("ColorChooserDemo");
 
        // set default close operation of the window.
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        // Create and set up the content pane.
        JComponent newContentPane = new ColorChooserDemo();
 
        // content panes must be opaque
        newContentPane.setOpaque(true);
 
        // add content pane to the frame
        frame.setContentPane(newContentPane);
 
        // Display the window.
        frame.pack();
        frame.setVisible(true);
    }
 
    // Main Method
    public static void main(String[] args)
    {
 
        // Schedule a job for the event-dispatching thread:
        // creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
 
            public void run()
            {
 
                createAndShowGUI();
            }
        });
    }
}


Java
// Java program to implement JColorChooser
// class using ActionListener
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
 
public class ColorChooserExample extends
      JFrame implements ActionListener {
 
    // create a button
    JButton b = new JButton("color");
 
    Container c = getContentPane();
 
    // Constructor
    ColorChooserExample()
    {
 
        // set Layout
        c.setLayout(new FlowLayout());
 
        // add Listener
        b.addActionListener(this);
 
        // add button to the Container
        c.add(b);
    }
 
    public void actionPerformed(ActionEvent e)
    {
 
        Color initialcolor = Color.RED;
 
        // color chooser Dialog Box
        Color color = JColorChooser.showDialog(this,
                    "Select a color", initialcolor);
 
        // set Background color of the Container
        c.setBackground(color);
    }
 
    // Main Method
    public static void main(String[] args)
    {
 
        ColorChooserExample ch = new ColorChooserExample();
        ch.setSize(400, 400);
        ch.setVisible(true);
        ch.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}


输出:

2、 Java程序使用ActionListener实现JColorChooser类:创建一个按钮和一个容器,并设置容器的布局。将ActionListener()添加到按钮,并将按钮添加到容器。 ActionListerner()有一个方法actionPerformed() ,只要单击按钮就会实现。选择颜色并设置容器的背景颜色。

Java

// Java program to implement JColorChooser
// class using ActionListener
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
 
public class ColorChooserExample extends
      JFrame implements ActionListener {
 
    // create a button
    JButton b = new JButton("color");
 
    Container c = getContentPane();
 
    // Constructor
    ColorChooserExample()
    {
 
        // set Layout
        c.setLayout(new FlowLayout());
 
        // add Listener
        b.addActionListener(this);
 
        // add button to the Container
        c.add(b);
    }
 
    public void actionPerformed(ActionEvent e)
    {
 
        Color initialcolor = Color.RED;
 
        // color chooser Dialog Box
        Color color = JColorChooser.showDialog(this,
                    "Select a color", initialcolor);
 
        // set Background color of the Container
        c.setBackground(color);
    }
 
    // Main Method
    public static void main(String[] args)
    {
 
        ColorChooserExample ch = new ColorChooserExample();
        ch.setSize(400, 400);
        ch.setVisible(true);
        ch.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

输出:

注意:上述程序可能无法在在线 IDE 中运行。请使用离线编译器。
参考: https://docs.oracle.com/javase/7/docs/api/javax/swing/JColorChooser.html