Example from lab 1/10/01
Note: The use of static below was a quick fix and we will discuss later. Normally this is not the approach to use.
import javax.swing.*; // Import the Swing classes
import java.awt.event.*; // for the WindowAdapter and WindowEvent classes
import java.awt.*; // for the Container class
// This is your Swing applet (by extending JApplet).
public class THelloApplicationOnly {
static JFrame f = new JFrame("THello");
static JLabel l = new JLabel("My New Label");
static JLabel lab2 = new JLabel("Second label");
static JTextArea ta = new JTextArea("Init. string", 10, 30);
static JScrollPane sp = new JScrollPane(ta);
// When you run this program as an application.
// The main method instantiates the application frame.
public static void main(String[] args) {
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Container c = f.getContentPane();
c.setLayout(new FlowLayout( FlowLayout.CENTER, 20, 30 ));
// Add the applet to the JFrame (to it's content pane).
c.add(l);
c.add(lab2);
c.add(sp);
// Add the listener to close the frame.
f.addWindowListener(new WindowEventHandler());
// Assign the frame size and display it.
f.setSize(400, 300); // frame: width=300, height = 150
f.show(); // Display the frame
forLoop(15);
}
private static void forLoop(int howMany) {
ta.setText("");
for (int i = 0; i < howMany; i++) {
ta.append("" + i + '\n');
}
}
}
import java.awt.event.*;
// Class to close the frame and exit the application.
public class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}