日期:2014-05-20 浏览次数:20659 次
package cn.ts.jfilechooser; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileInputStream; import java.util.Scanner; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Demo { public static void main(String args[]){ new Note(); } } class Note implements ActionListener { private JTextArea area=new JTextArea(8,10); private JFrame frame=new JFrame("文件选择"); private JButton open=new JButton("打开文件"); private JButton save=new JButton("存储文件"); private JLabel lab=new JLabel("现在没有打开文件"); private JPanel pan=new JPanel(); public void Note(){ this.pan.add(open); this.pan.add(save); frame.setLayout(new BorderLayout(3,3)); frame.add(this.lab); frame.add(this.pan); frame.add(new JScrollPane(this.area),BorderLayout.CENTER); this.frame.setSize(330,180); this.frame.setVisible(true); this.frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(1); } }); this.open.addActionListener(this); this.save.addActionListener(this); frame.setSize(300,200); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub File file=null; int result=0; JFileChooser fileChooser=new JFileChooser(); if(arg0.getSource()==this.open){ this.area.setText(""); fileChooser.setApproveButtonText("确定"); fileChooser.setDialogTitle("打开文件"); result=fileChooser.showOpenDialog(this.frame); if(result==JFileChooser.APPROVE_OPTION){ file=fileChooser.getSelectedFile(); this.lab.setText("打开的文件名称"+file.getName()); }else if(result==JFileChooser.CANCEL_OPTION){ this.lab.setText("没有选择文件"); }else{ this.lab.setText("操作有误"); } if(file!=null){ try{ Scanner scan=new Scanner(new FileInputStream(file)); scan.useDelimiter("\n"); while(scan.hasNext()){ this.area.append(scan.next()); this.area.append("\n"); } scan.close(); }catch(Exception e){ this.lab.setText("读文件出错"); } } } } }
public static void main(String args[]){ new Note(); }