//TextEd.java //a simple text editor import java.awt.*; import java.awt.event.*; import java.io.*; import WindowCloser; public class TextEd extends Frame{ TextArea txtOutput = new TextArea(20, 40); Button cmdOpen = new Button("open"); Button cmdSave = new Button("save"); Button cmdQuit = new Button("quit"); Panel pnlNorth = new Panel(); HandleButtons hb = new HandleButtons(); WindowCloser wc; public static void main(String args[]){ TextEd te = new TextEd(); te.setSize(200,200); te.pack(); te.show(); } // end main TextEd(){ super("Simple Text editor"); setLayout(new BorderLayout()); add(pnlNorth, BorderLayout.NORTH); pnlNorth.setLayout(new FlowLayout()); pnlNorth.add(cmdOpen); pnlNorth.add(cmdSave); pnlNorth.add(cmdQuit); cmdOpen.addActionListener(hb); cmdSave.addActionListener(hb); cmdQuit.addActionListener(hb); add(txtOutput, BorderLayout.CENTER); wc = new WindowCloser((Window)this); addWindowListener(wc); } // end constructor public void openFile(){ //request a filename, and open the file FileDialog fd = new FileDialog(this, "open a file"); fd.setMode(FileDialog.LOAD); fd.setDirectory("."); fd.setFile("*.txt"); fd.show(); File myFile = new File(fd.getFile()); try { BufferedReader in = new BufferedReader(new FileReader(myFile)); txtOutput.setText(""); String line = ""; while (line != null) { line = in.readLine(); if (line != null) txtOutput.append(line + "\n"); } // end while in.close(); } catch (IOException e) { System.out.println(e.getMessage()); } // end try }// end openFile public void saveFile(){ //request a filename and save the file FileDialog fd = new FileDialog(this, "save the file"); fd.setMode(FileDialog.SAVE); fd.setDirectory("."); fd.setFile("*.txt"); fd.show(); File myFile = new File(fd.getFile()); try{ PrintWriter out = new PrintWriter(new FileWriter(myFile)); out.print(txtOutput.getText()); out.close(); } catch (IOException e){ System.out.println(e.getMessage()); } // end try } // end saveFile private class HandleButtons implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getSource() == cmdOpen){ openFile(); } else if (e.getSource() == cmdSave){ saveFile(); } else if (e.getSource() == cmdQuit){ dispose(); System.exit(0); } //end if } // end actionPerformed } //end handleButtons } // end classDef