public class Notepad extends JFrame implements actionlistener{
Define the required components
JTextArea JTA = null;
Menu bar
JMenuBar JMB = null;
First JMenu
JMenu jm1 = null;
Define JMenuItem
JMenuItem jmi1 = null;
JMenuItem jmi2 = null;
public static void Main (string[] args) {
Notepad NP = new Notepad ();
}
constructor function
Public Notepad () {
Create JTA
JTA = new JTextArea ();
JMB = new JMenuBar ();
JM1 = new JMenu ("file");
Setting mnemonics
Jm1.setmnemonic (' F ');
JMI1 = new JMenuItem ("open");
Register for monitoring
Jmi1.addactionlistener (this);
Jmi1.setactioncommand ("open");
Jmi2 = new JMenuItem ("Save");
To save menu processing
Jmi2.addactionlistener (this);
Jmi2.setactioncommand ("Save");
Join
This.setjmenubar (JMB);
Put JM1 into JMB.
Jmb.add (JM1);
Put Item into menu
Jm1.add (JMI1);
Jm1.add (JMI2);
Put into the JFrame
This.add (JTA);
This.setdefaultcloseoperation (Jframe.exit_on_close);
This.setsize (400,300);
This.setvisible (TRUE);
}
@Override
public void actionperformed (ActionEvent e) {
Which menu is selected when judging
if (E.getactioncommand (). Equals ("open")) {
System.out.println ("open");
Important Components: JFileChooser
File Selection Component
JFileChooser jfc1 = new JFileChooser ();
Set name
Jfc1.setdialogtitle ("Please select File ...");
Default mode
Jfc1.showopendialog (NULL);
Show
Jfc1.setvisible (TRUE);
Get the full path of the user-selected file
String filename = Jfc1.getselectedfile (). GetAbsolutePath ();
SYSTEM.OUT.PRINTLN (filename);
FileReader FR = null;
BufferedReader br = null;
try {
FR = new FileReader (filename);
br = new BufferedReader (FR);
Reads the information from the file and displays it to the JTA
String s = "";
String allcontent = "";
while ((s = br.readline ())!=null) {
System.out.println (s); Output file contents to the console
Output to disk
allcontent+=s+ "\ r \ n";
}
Large JTA can be placed
Jta.settext (allcontent);
} catch (Exception E1) {
}finally{
try {
Br.close ();
Fr.close ();
} catch (Exception E1) {
E1.printstacktrace ();
}
}
}else if (E.getactioncommand (). Equals ("Save")) {
The Save dialog box appears
JFileChooser JFC = new JFileChooser ();
Jfc.setdialogtitle ("Save As ...");
Display by default
Jfc.showsavedialog (NULL);
Jfc.setvisible (TRUE);
Get where the user wants to save the file--full path to the file
String file = Jfc.getselectedfile (). GetAbsolutePath ();
Preparing to write to the specified file
FileWriter FW = NULL;
BufferedWriter bw = NULL;
try {
FW = new FileWriter (file);
BW = new BufferedWriter (FW);
Can be optimized by itself
Bw.write (This.jta.getText ());
} catch (Exception E2) {
E2.printstacktrace ();
}finally{
try {
Bw.close ();
Fw.close ();
} catch (Exception E3) {
}
}
}
}
}
Notepad read-Write file function implementation