public class JColorChooserDemo extends JFrame {
private Container container; // 容器
private JPanel colorPanel; // 用于反映颜色变化的面板
public JColorChooserDemo() { // 构造函数
super("调色板演示"); // 调用JFrame的构造函数
container = getContentPane(); // 得到容器
colorPanel = new JPanel(); // 初始化面板
final JButton selectColorButton = new JButton("选取颜色"); // 初始化颜色选择按钮
final JTextField jt = new JTextField();
jt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String cmd = jt.getText();
Random r = new Random();
if (cmd.equals("r")) {
int red = r.nextInt(256);
int green = r.nextInt(256);
int blue = r.nextInt(256);
colorPanel.setBackground(new Color(red, green, blue));
selectColorButton.setText((red + "," + green + "," + blue));
} else if (cmd.contains("*") && cmd.contains(",")) {
while (cmd.contains("*"))
cmd = cmd.replaceFirst("\\*", r.nextInt(256) + "")
.toString();
String[] c = cmd.split(",");
colorPanel.setBackground(new Color(Integer.valueOf(c[0]),
Integer.valueOf(c[1]), Integer.valueOf(c[2])));
selectColorButton.setText((c[0] + "," + c[1] + "," + c[2]));
}
}
});
selectColorButton.addActionListener( // 为颜色选择按钮增加事件处理
new ActionListener() {
public void actionPerformed(ActionEvent event) {
Color color = JColorChooser
.showDialog(JColorChooserDemo.this, "选取颜色",
Color.lightGray); // 得到选择的颜色
if (color == null) // 如果未选取
color = Color.gray; // 则设置颜色为灰色
colorPanel.setBackground(color); // 改变面板的背景色
jt.setText(color.getRed() + "," + color.getGreen()
+ "," + color.getBlue());
}
});
container.add(selectColorButton, BorderLayout.NORTH); // 增加组件
container.add(colorPanel, BorderLayout.CENTER); // 增加组件
container.add(jt, "South");
setSize(400, 230); // 设置窗口尺寸
setLocationRelativeTo(null); // 正中显示
setVisible(true); // 设置窗口可见
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口时退出程序
}
public static void main(String args[]) {
new JColorChooserDemo();
}
}
[img]http://dl.iteye.com/upload/attachment/538656/384198d3-61bc-3728-82f6-2c5d6fd0e827.jpg[/img]
很不错的swing调色板。