爱玺玺

爱玺玺的生活日记本。wx:lb87626

简单记事本程序,和前面的差不多

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;


import javax.swing.ImageIcon;

import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;


public class NotePad extends JFrame implements ActionListener{

JScrollPane jsp=null;

JTextArea jta=null;

JMenuBar jmb=null;

JMenu jm=null;

JMenuItem jmi1=null;

JMenuItem jmi2=null;

//构造方法

    public NotePad() {

jta=new JTextArea();

jsp=new JScrollPane(jta);

jmb=new JMenuBar();

jm=new JMenu("文件");

jmi1=new JMenuItem("打开");

jmi1.addActionListener(this);

jmi2=new JMenuItem("另存为");

jmi2.addActionListener(this);

jm.add(jmi1);

jm.add(jmi2);

jmb.add(jm);

this.add(jmb,"North");

this.add(jsp);

}

    //main

    public static void main(String[] args){

    NotePad np=new NotePad();

    np.setSize(400,600);

    ImageIcon ico=new ImageIcon(np.getClass().getResource("/createNew.jpg"));

    np.setIconImage(ico.getImage());

    np.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    np.setTitle("记事本");

    np.setVisible(true);

    }

@Override

public void actionPerformed(ActionEvent e) {

if(e.getActionCommand().equals("打开")){

JFileChooser jfc=new JFileChooser();

jfc.showOpenDialog(null);

String file=jfc.getSelectedFile().getAbsolutePath();

FileReader fr=null;

BufferedReader br=null;

try{

fr=new FileReader(file);

br=new BufferedReader(fr);

/**这两个字符串变量必须要**/

String conStr="";

String tmpStr="";

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

//conStr+=br.readLine()+"\r\n";//不能这么写,不然没运行一次br.readLine()指针就会移动

   conStr+=tmpStr+"\r\n";

}

jta.setText(conStr);

}catch(Exception e1){

e1.printStackTrace();

}finally{

try {

br.close();

fr.close();

} catch (Exception e2) {

// TODO: handle exception

}

}

jfc.setVisible(true);

}else if(e.getActionCommand().equals("另存为")){

JFileChooser jfc=new JFileChooser();

jfc.showSaveDialog(null);

jfc.setVisible(true);

String content=jta.getText();

String file=jfc.getSelectedFile().getAbsolutePath();

FileWriter fw=null;

BufferedWriter bw=null;

try {

fw=new FileWriter(file);

bw=new BufferedWriter(fw);

bw.write(content);

bw.flush();

} catch (Exception e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}finally{

try {

bw.close();

fw.close();

} catch (Exception e2) {

// TODO: handle exception

}

}

}

}

}


发表评论:

Powered By Z-BlogPHP 1.4 Deeplue Build 150101

Copyright Your WebSite.Some Rights Reserved.

蜀ICP备11021721号-5