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

博为峰小博老师:

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

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

publicclassBWFimplementsActionListener{

JFramef=null;

JLabellabel=null;

JTextAreatextArea=null;

JFileChooserfileChooser;

publicBWF() {

f=newJFrame("博为峰教育");

MyPanelpanel=newMyPanel();

f.getContentPane().add(panel);

f.pack();

f.setVisible(true);

f.addWindowListener(newWindowAdapter() {

@Override

publicvoidwindowClosing(WindowEvente) {

System.exit(0);

}

});

}

publicstaticvoidmain(String[]args) {

newBWF();

}

@Override

publicvoidactionPerformed(ActionEvente) {

Filefile=null;

intresult;

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

}

elseif(result==JFileChooser.CANCEL_OPTION){

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

}

FileInputStreamfileInputStream=null;

if(file!=null){

try{

fileInputStream=newFileInputStream(file);

}catch(Exceptione1){

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

return;

}

Stringreadbyte=null;

try{

BufferedReaderbr=newBufferedReader(newInputStreamReader(fileInputStream));

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

textArea.setLineWrap(true);

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

}

}catch(Exceptione1){

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

}finally{

try{

if(fileInputStream!=null){

fileInputStream.close();

}

}catch(Exceptione1){

}

}

}

}

}

classMyPanelextendsJPanelimplementsActionListener{

privateJButtonbutton,rgb,red,green,blue;

privateColorcolor=newColor(0,0,0);

publicMyPanel() {

button=newJButton("获得颜色");

rgb=newJButton("RGB");

red=newJButton("Red");

green=newJButton("Green");

blue=newJButton("Blue");

button.addActionListener(this);

setPreferredSize(newDimension(550, 250));

setLayout(newFlowLayout(FlowLayout.CENTER,5,5));

setBackground(color);

add(button);add(rgb);add(red);add(green);add(blue);

}

@Override

publicvoidactionPerformed(ActionEvente) {

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

}

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容