Computer Science 15-100 (Sections T & U), Spring 2008
Notes:  Bonus Lecture #6

Simple Introduction to Swing and Applets


Logistics:


Note:  this was a very quick lecture.  The code we wrote just skims the surface of Swing and Applets.  Fortunately, there are many fine online tutorials and physical books you can buy on the subject.  So get to it!  :-)

Code from class:  you can run our code from class as an application, or you can run it as an applet.  Here is the html to run it as an applet:

<html>
<body>
This demonstrates the SwingDemo applet. Woo hoo.
<hr>
<applet code="SwingDemo.class" width=600 height=400 />
<hr> 
Wow, that was cool.
</body>
</html>

Here is the actual applet using this html:  SwingDemo.html

And here is the code SwingDemo.java:

// SwingDemo.java
// A very brief demo of creating a Swing-based application and/or applet
// Code written quickly in class on 1-May-08 (and so may not have ideal style, etc...)

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

public class SwingDemo extends JApplet {

  private boolean isApplet = false;
  
  // This is ONLY CALLED IF WE ARE AN APPLICATION AND NOT AN APPLET
  public static void main(String[] args) {
    new SwingDemo().launchApp();
  }
  
  // This is ONLY CALLED IF WE ARE AN APPLET AND NOT AN APPLICATION
  public void start() {
    this.isApplet = true;
    start(this.getContentPane());
  }
  
  public void saveToFile(String filename, String text) {
    try {
      PrintStream out = new PrintStream(new File(filename));    
      out.print(text);    
    }
    catch (Exception e) {
      String s = "Could not save to file: " + filename;
      if (this.isApplet) s += " (as expected for an applet)";
      JOptionPane.showMessageDialog(null, s, "error", JOptionPane.ERROR_MESSAGE);
    }
  }
  
  public String getTextFromFile(String filename) {
    try {
      Scanner scanner = new Scanner(new File(filename));
      StringBuffer sb = new StringBuffer();
      while (scanner.hasNext()) {
        sb.append(scanner.nextLine());
        sb.append("\n");
      }
      fileTextField.setText(filename);
      return sb.toString();
    }
    catch (Exception e) {
      String s = "Could not open file: " + filename;
      if (this.isApplet) s += " (as expected for an applet)";
      return s;
    }
  }

  private JTextPane textPane = new JTextPane();
  private JTextField fileTextField = new JTextField("a.txt", 20);
  
  public void doSaveAction() {
    saveToFile(fileTextField.getText(),textPane.getText());
  }

  public void doLoadAction() {
    textPane.setText(getTextFromFile(fileTextField.getText()));
  }

  
  public void launchApp() {
    JFrame frame = makeFrame("SwingDemo");
    Container cp = frame.getContentPane();
    start(cp);
    frame.pack();
    frame.setVisible(true);
  }
  
  // shared by both the applet and the application code
  private void start(Container cp) {
    JPanel northBar = new JPanel();
    northBar.setLayout(new FlowLayout());    
    northBar.add(new JLabel("file:"));
    northBar.add(fileTextField);
    
    ActionListener listener = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String action = e.getActionCommand();
        if (action.equals("save"))
          doSaveAction();
        else if (action.equals("load"))
          doLoadAction();
        else
          Toolkit.getDefaultToolkit().beep();
      }
    };

    JButton saveButton = new JButton("save");
    saveButton.setMnemonic(KeyEvent.VK_S);
    saveButton.setToolTipText("Save the current contents to the given file");
    saveButton.setActionCommand("save");
    saveButton.addActionListener(listener);
    
    JButton loadButton = new JButton("load");
    loadButton.setActionCommand("load");
    loadButton.addActionListener(listener);

    northBar.add(saveButton);
    northBar.add(loadButton);
    
    // textPane.setBackground(new Color(220,220,255));
    textPane.setBackground(Color.blue);
    textPane.setForeground(Color.white);
    textPane.setFont(new Font("courier",Font.BOLD,24));
    textPane.setText(getCeleryText());
    
    JScrollPane sp = new JScrollPane(textPane);

    cp.setLayout(new BorderLayout());
    cp.add(northBar,BorderLayout.NORTH);
    cp.add(sp,BorderLayout.CENTER);
  }
  
  public static JFrame makeFrame(String title) {
    JFrame frame = new JFrame(title);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    return frame;
  }
  
  public static String getCeleryText() {
    return "Celery\n" +
           "By Ogden Nash\n" +
           "\n" +
           "Celery, raw\n" +
           "Develops the jaw,\n" +
           "But celery, stewed,\n" +
           "Is more quietly chewed.\n";
  }
}

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem