Programming Resources
For Fun and Learning
Charles Cusack
Computer Science
Hope College
main

Python
C++

JAVA


PHP
SQL
Assignments

HTMLeditor


HTMLEditor.java

 import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.io.*;

/**
 * This is a very simple HTML editor.  The point is to demonstrate how
 * to use JFileChooser to get a file from the filesystem, and to show
 * how to display HTML using a JEditorPane
 *
 */
public class HTMLEditor extends JFrame {

  JEditorPane outputPane; // This will allow us tp display HTML
  JTextArea theText;

  JFileChooser fc;
  
  public HTMLEditor() {
    Container contentPane =  this.getContentPane();
    contentPane.setLayout(new BorderLayout());
    this.setTitle("A very simple HTML editor");

    JButton readButton = new JButton("Open");
    JButton writeButton = new JButton("Save");
    JButton updateButton = new JButton("Update View");
    
    Box buttonBox=Box.createHorizontalBox();
    buttonBox.add(updateButton);
    buttonBox.add(readButton);
    buttonBox.add(writeButton);
    
    theText= new JTextArea(10,70);
    theText.setBorder(new TitledBorder("HTML Source"));
    
    outputPane = new JEditorPane();
    
    // This line must be included.  If it is not, the text will be
    // rendered as plain text.
    outputPane.setContentType("text/html");
    // Always a good idea to not allow editing in output windows
    outputPane.setEditable(false);
    outputPane.setBorder(new TitledBorder("HTML Rendered"));
    
    JPanel textPanel = new JPanel();
    textPanel.setLayout(new GridLayout(2,1));
    textPanel.add(new JScrollPane(theText));
    textPanel.add(new JScrollPane(outputPane));
    
    this.getContentPane().add(buttonBox, BorderLayout.NORTH);
    this.getContentPane().add(textPanel, BorderLayout.CENTER);
    
    // A JFileChooser is used to get access to files from the file system.
    // You can do more interesting things file file choosers, like restrict
    // the sorts of files that it will show.  For simplicity, I have not
    // done that for this example.
    //
    fc = new JFileChooser();
    
    
    updateButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        outputPane.setText(theText.getText());
      } });

    readButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        openFile();
      } });

    writeButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        saveFile();
      } });
      
      pack();
      this.setSize(new Dimension(800,800));
      setVisible(true);
    }
    
  /**Overridden so we can exit when window is closed*/
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
      System.exit(0);
    }
  }
  /**
   * The main method so we can run the class as an application.
   */
  public static void main(String[] args) {
      new HTMLEditor();
  }

  public void openFile() {
        // This will pop up a window which allows the user to pick a 
        // file from the file system.
        int returnVal = fc.showDialog(this,"Open");
        
        // We check whether or not they clicked the "Open" button
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            // We get a reference to the file that the user selected.
            File file = fc.getSelectedFile();
            // Make sure it actually exists.
            if(!file.exists()) {
                JOptionPane.showMessageDialog(this,
                     "That file does not exist!.",
                     "File Error", JOptionPane.INFORMATION_MESSAGE);
            } else {
                // Apparently all is well, so go ahead and read the file.
                 readFile(file);
            }
        }
  }
         
  public void readFile(File theFile) {
     try {
          FileReader inStream=new FileReader(theFile);
          BufferedReader inData=new BufferedReader(inStream);
          StringBuffer theInput=new StringBuffer("");
          String in=inData.readLine();
          while(in!=null) {
             theInput.append(in+"\n");
             in=inData.readLine();
          }
          inData.close();
          theText.setText(theInput.toString());
          
          // This works only if the file has a .html or .htm extension.
      // If the file has a different extension it will probably render
      // it as plain text.
      //
      // You could also use
      //      outputPane.setText(theInput.toString());
      // but it might take longer to render it.
          outputPane.setPage(theFile.toURL());
     }      
     catch(IOException e) {
          System.out.println("Error opening file");
     }
  }
  
  void saveFile() {
      // Pop up a window so the user can select a file to save to.
      int returnVal = fc.showDialog(this,"Save");
      // Make sure they clicked on the "Save" button
      if(returnVal == JFileChooser.APPROVE_OPTION) {
           // Get the file they selected 
           File file = fc.getSelectedFile();
           
           // If the file exists, we want to warn the user so they
           // don't accidently overwrite a file.
           if(file.exists()) {
            Object[] options = {"Overwrite?","Cancel"};
            int n = JOptionPane.showOptionDialog(this,
                 "The file exists.  Do you want to:\n"+
                 "1) Overwrite the existing file \n"+
                 "   (all data in the file will be discarded)\n"+
                 "2) Cancel the operation",
                 "File exists: overwrite or append?",
                 JOptionPane.YES_NO_OPTION,
                 JOptionPane.QUESTION_MESSAGE,
                 null,     //don't use a custom Icon
                 options,  //the titles of buttons
                 options[1]); //default button title
             switch (n) {
                // They want to write to the file, so delete it and write it.
                case JOptionPane.YES_OPTION:
                     file.delete();
                     writeFile(file);
                    break;
                case JOptionPane.NO_OPTION:
                    JOptionPane.showMessageDialog(this,
                          "Operation cancelled.  The file will not be saved.",
                          "Not saving", JOptionPane.INFORMATION_MESSAGE); 
                break;
             }
          } else { // The file does not exist, so write to it.
             writeFile(file);
          }
      }
  }
    
  public void writeFile(File theFile) {
     try {
          FileWriter outStream=new FileWriter(theFile);
          PrintWriter outData=new PrintWriter(outStream);
          String outputText=theText.getText();
          outData.print(outputText);
          outData.close();
     }
     catch(IOException e) {
          System.out.println("Error opening file");
     }
  }
}