📅  最后修改于: 2020-09-30 06:09:08             🧑  作者: Mango
JColorChooser类用于创建颜色选择器对话框,以便用户可以选择任何颜色。它继承了JComponent类。
我们来看一下javax.swing.JColorChooser类的声明。
public class JColorChooser extends JComponent implements Accessible
Constructor | Description |
---|---|
JColorChooser() | It is used to create a color chooser panel with white color initially. |
JColorChooser(color initialcolor) | It is used to create a color chooser panel with the specified color initially. |
Method | Description |
---|---|
void addChooserPanel(AbstractColorChooserPanel panel) | It is used to add a color chooser panel to the color chooser. |
static Color showDialog(Component c, String title, Color initialColor) | It is used to show the color chooser dialog box. |
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class ColorChooserExample extends JFrame implements ActionListener {
JButton b;
Container c;
ColorChooserExample(){
c=getContentPane();
c.setLayout(new FlowLayout());
b=new JButton("color");
b.addActionListener(this);
c.add(b);
}
public void actionPerformed(ActionEvent e) {
Color initialcolor=Color.RED;
Color color=JColorChooser.showDialog(this,"Select a color",initialcolor);
c.setBackground(color);
}
public static void main(String[] args) {
ColorChooserExample ch=new ColorChooserExample();
ch.setSize(400,400);
ch.setVisible(true);
ch.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
输出:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ColorChooserExample extends JFrame implements ActionListener{
JFrame f;
JButton b;
JTextArea ta;
ColorChooserExample(){
f=new JFrame("Color Chooser Example.");
b=new JButton("Pad Color");
b.setBounds(200,250,100,30);
ta=new JTextArea();
ta.setBounds(10,10,300,200);
b.addActionListener(this);
f.add(b);f.add(ta);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
Color c=JColorChooser.showDialog(this,"Choose",Color.CYAN);
ta.setBackground(c);
}
public static void main(String[] args) {
new ColorChooserExample();
}
}
输出: