您的位置:首页 > 编程语言 > Java开发

博为峰Java技术文章 ——JavaSE 如何使用颜色选取器JColorChooser

2017-04-23 00:00 323 查看
博为峰小博老师:

ColorChooser可以让用户选择自己想要的颜色并更改某个组件的颜色,并选择各式各样的颜色来加以装饰。至于颜色的选择,可以找到颜色选择对话框。颜色选择对话框可以通过使用颜色选取器来创建。

颜色选取器JColorChooser的构造器的说明如下所示。





public class BWF implements ActionListener{

JFrame f=null;

JLabel label=null;

JTextArea textArea=null;

JFileChooser fileChooser;

public BWF() {

f=new JFrame("博为峰教育");

MyPanel panel=new MyPanel();

f.getContentPane().add(panel);

f.pack();

f.setVisible(true);

f.addWindowListener(new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

}

public static void main(String[] args) {

new BWF();

}

@Override

public void actionPerformed(ActionEvent e) {

File file=null;

int result;

if(e.getActionCommand().equals("新建文件")){

fileChooser.setApproveButtonText("确定");

fileChooser.setDialogTitle("打开文件");

result=fileChooser.showOpenDialog(f);

textArea.setText("");

if(result==JFileChooser.APPROVE_OPTION){

file=fileChooser.getSelectedFile();

label.setText("你打开的文件名为:"+file.getName());

}

else if(result==JFileChooser.CANCEL_OPTION){

label.setText("你没有选择任何文件");

}

FileInputStream fileInputStream=null;

if(file!=null){

try{

fileInputStream=new FileInputStream(file);

}catch(Exception e1){

label.setText("没找到文件");

return;

}

String readbyte=null;

try{

BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream));

while((readbyte=br.readLine())!=null){

textArea.setLineWrap(true);

textArea.append(String.valueOf(readbyte));

}

}catch(Exception e1){

label.setText("读取文件错误");

}finally {

try{

if(fileInputStream!=null){

fileInputStream.close();

}

}catch(Exception e1){

}

}

}

}

}

class MyPanel extends JPanel implements ActionListener{

private JButton button,rgb,red,green,blue;

private Color color = new Color(0,0,0);

public MyPanel() {

button=new JButton("获得颜色");

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

}

@Override

public void actionPerformed(ActionEvent e) {

color=JColorChooser.showDialog(this, "颜色选择器", color);

setBackground(color);

button.setText("RGB:"+color.getRGB());

rgb.setText("Red:"+color.getRed());

green.setText("Green:"+color.getGreen());

blue.setText("Blue:"+color.getBlue());

}

}

}











内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐