Knowledge points involved: Gui, I/O operations, and event listening. The sample code is as follows:
package ioTest;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
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.JTextArea;
public class NotePad extends JFrame implements ActionListener{
JTextArea jta=null;
JMenuBar jmb=null;
JMenu jm=null;
JMenuItem jmi=null;
JMenuItem jmi2=null;
public static void main(String[] args) {
NotePad np=new NotePad();
}
public NotePad(){
jta=new JTextArea();
jmb=new JMenuBar();
JM = new JMenu ("file");
JM. Setmnemonic ('f '); / / set shortcut key
JMI = new jmenuitem ("open", new imageicon ("D: \ \ javaspace \ \ test_1 \ \ SRC \ \ 3. GIF"));
//Register to listen
jmi.addActionListener(this);
jmi.setActionCommand("open");
Jmi2 = new jmenuitem ("save");
jmi2.addActionListener(this);
jmi2.setActionCommand("save");
this.setJMenuBar(jmb);
Jmb.add (JM);
Jm.add (JMI);
jm.add(jmi2);
this.add(jta);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,300);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand().equals("open")){
//The select file dialog box appears
JFileChooser jfc=new JFileChooser();
Jfc.setdialogtitle ("please select File...");
Int value = JFC. Showopendialog (null); / / display by default
jfc.setVisible(true);
if(value==JFileChooser.APPROVE_OPTION){
String filename=jfc.getSelectedFile().getAbsolutePath();
//System.out.println("test");
FileReader fr=null;
BufferedReader br=null;
Try{
fr=new FileReader(filename);
br=new BufferedReader(fr);
String s,all = "";
while((s=br.readLine())!=null){
all+=s+"\r\n";
}
jta.setText(all);
}catch(Exception e){
e.printStackTrace();
}finally{
Try {
Br.close ();
Fr.close ();
} catch (Exception e2) {
}
}
}Else {/ / click Jfilechooser to close the button without doing any work
}
}else if(arg0.getActionCommand().equals("save")){
//The save dialog box appears
JFileChooser jfc=new JFileChooser();
Jfc.setdialogtitle ("save as...");
int value=jfc.showSaveDialog(null);
jfc.setVisible(true);
if(value==JFileChooser.APPROVE_OPTION){
String filename=jfc.getSelectedFile().getAbsolutePath();
FileWriter fw=null;
BufferedWriter bw=null;
Try{
fw=new FileWriter(filename);
bw=new BufferedWriter(fw);
bw.write(jta.getText());
}catch(Exception e){
e.printStackTrace();
}finally{
Try {
Bw.close ();
Fw.close ();
} catch (Exception e2) {
}
}
}else{
}
}
}
}