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

博为峰Java技术文章 ——JavaSE 如何创建JFileChooser对话框

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

JFileChooser对话框演示代码如下所示:

public class BWF implements ActionListener{

JFrame f=null;

JLabel label=null;

JTextArea textArea=null;

JFileChooser fileChooser;

public BWF() {

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

Container contentPane=f.getContentPane();

textArea=new JTextArea();

JScrollPane scrollPane=new JScrollPane(textArea);

scrollPane.setPreferredSize(new Dimension(350, 300));

JPanel panel=new JPanel();

JButton b1=new JButton("新建文件");

b1.addActionListener(this);

JButton b2=new JButton("退出文件");

b2.addActionListener(this);

panel.add(b1);

panel.add(b2);

label=new JLabel("",JLabel.CENTER);

//建立一个FileChooser对象,指定D盘目录为默认文件对话框路径

fileChooser=new JFileChooser("D:\\");

contentPane.add(label,BorderLayout.NORTH);

contentPane.add(scrollPane,BorderLayout.CENTER);

contentPane.add(panel,BorderLayout.SOUTH);

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

}

}

}

}

}

}











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