Swing调色板小工具:支持随机取色或随机某一色系取色

1,在输入行输入"r":让不错的颜色随机发生。
2,输入行输入:"128,*,128":根据RGB(红绿蓝)顺序,则让红蓝保持,只让绿变动。通配符而已。某一色系的配色,可以让观者不觉花哨和凌乱。
3,如你所见,"*,*,*"命令其实也是全色系随机。:-)
4,Swing的调色板组件也可以调出。

 @SuppressWarnings("serial")
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();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值