Java Swing中的JButton、JComboBox、JList和JColorChooser组件使用案例(6)
最常使用JColorChooser的方式是使用JColorChooser的静态方法showDialog().也就是说在大部份的情况下,我们不会new一个JColorChooser对象,而是直接使用JColorChooser的静态方法(showDialog())来输出颜色选择对话框.利用这个方法我们亦可以得到用户所选择的颜色,若用户没有选择则返回null值.
颜色选择对话框的简单案例1代码:
public class JColorChooserDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("JColorChooserDemo");
MyPanel panel = new MyPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setLocation(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MyPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton button,rgb,red,green,blue;
private Color color = new Color(255, 51, 150);
public MyPanel() {
button = new JButton("Get Color");
rgb = new JButton("RGB: ");
red = new JButton("Red: ");
green = new JButton("Green: ");
blue = new JButton("Blue: ");
button.addActionListener(this);
setPreferredSize(new Dimension(550, 250));
setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
setBackground(color);
add(button);
add(rgb);
add(red);
add(green);
add(blue);
}
public void actionPerformed(ActionEvent e) {
color = JColorChooser.showDialog(this, "Choose Color", color);
if (color != null) {
setBackground(color);
button.setText("Get again");
rgb.setText("RGB: " + color.getRGB());
red.setText("Red: " + color.getRed());
green.setText("Green: " + color.getGreen());
blue.setText("Blue: " + color.getBlue());
}
}
}
运行结果示意图如下:
另外还有一个使用JColorChooser常用的方式,那就是使用createDialog()静态方法.使用这个静态方法后会得到一个JDialog对象,我们可以利用这个JDialog对象对颜色选择对话框做更多的设置.不过利用这个方法必须配合JColorChooser对象才行,也就是必须new出一个JColorChooser对象来.下面范例介绍最简单的也是最实用JColorChooser,选择颜色完毕后就能更改JLabel上的背景颜色.
颜色选择对话框的简单案例2代码: