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();
     }
 }

你可能感兴趣的:(C++,c,swing,C#)