java jfilechooser报错_Java实现简单记事本

importjava.awt.BorderLayout;importjava.awt.Container;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjavax.swing.JFileChooser;importjavax.swing.JFrame;importjavax.swing.JMenu;importjavax.swing.JMenuBar;importjavax.swing.JMenuItem;importjavax.swing.JScrollPane;importjavax.swing.JTextArea;public class NotepadDemo extends JFrame implementsActionListener {

JTextArea inputText;

JScrollPane pane;publicNotepadDemo() {this.setTitle("Notepad");this.setSize(600, 400);

setLocationRelativeTo(null);

setDefaultCloseOperation(EXIT_ON_CLOSE);

Container contentPane= this.getContentPane();

contentPane.setLayout(new BorderLayout(5,1));

JMenuBar menuBar= newJMenuBar();

JMenu menu= new JMenu("File");

JMenuItem open=new JMenuItem("打开...");

open.addActionListener(this);

menu.add(open);

JMenuItem save=new JMenuItem("存盘");

save.addActionListener(this);

menu.add(save);

menu.addSeparator();

JMenuItem item= new JMenuItem("退出");

menu.add(item);

item.addActionListener(this);

menuBar.add(menu);this.setJMenuBar(menuBar);

inputText=new JTextArea(100, 100);

pane=newJScrollPane(inputText);

contentPane.add(pane);

}public static voidmain(String[] args) {

JFrame frame= newNotepadDemo();

frame.setVisible(true);

}

@Overridepublic voidactionPerformed(ActionEvent event) {

String cmd=event.getActionCommand();if ("退出".equals(cmd)) {this.dispose();

}if ("打开...".equals(cmd)) {

File srcFile=null;

JFileChooser fileChooser=newJFileChooser();int res=fileChooser.showOpenDialog(null);if(res==JFileChooser.APPROVE_OPTION) {

srcFile=fileChooser.getSelectedFile();

}try{

InputStream is= newFileInputStream(srcFile);byte[] buffer = new byte[8*1024];intlen;while ((len = is.read(buffer)) != -1) {

String text= new String(buffer, 0, len,"UTF-8");

inputText.append(text);

}

is.close();

}catch(FileNotFoundException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}if ("存盘".equals(cmd)) {

File destFile=null;

JFileChooser fileChooser=newJFileChooser();int res = fileChooser.showSaveDialog(null);if (res ==JFileChooser.APPROVE_OPTION) {

destFile=fileChooser.getSelectedFile();

}else{

System.out.println("用户取消");return;

}try{

OutputStream os= newFileOutputStream(destFile);

os.write(inputText.getText().getBytes("UTF-8"));

os.close();

}catch(FileNotFoundException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值