// Java 2 // Toy example of a program usable as an application or as an applet. // Flexible is the program proper, such as it is. // GUI is the graphical user interface, such as it is. import java.lang.*; import java.applet.*; import java.awt.*; import java.awt.event.*; //----------------------------------------------------------------------------- public class Flexible extends Applet { static int s = 0; // stands for the State of the computation static GUI gui; // the GUI controls the computation // main & init would also initiate some "real" computation in a real problem public static void main(String[] argv) // required for an application { gui = new GUI(null); }//main public void init() // required for an applet { gui = new GUI(this); }//init // The routines below would do some "real" computing in a real problem: public static void action1() { s++; } // example computation public static void action2() { s--; } // -- " -- }//Flexible class //----------------------------------------------------------------------------- // java.lang.Object // |-java.awt.Component // |-java.awt.Container --lowest common ancestor of Applet & Frame // | // |-java.awt.Panel // | |-java.applet.Applet // | // |-java.awt.Window // |-java.awt.Frame class GUI { public Container c; // either the applet or a new frame boolean isFrame = false; Label stateDisplay; public GUI(Container c) { if(c == null) // called from main(), i.e. an application, not applet { final Frame f = new Frame(); f.setTitle("Flexible"); f.addWindowListener( new WindowAdapter() // for the close button { public void windowClosing(WindowEvent e) { f.dispose(); } } ); c = f; isFrame = true; } // new window Frame ! c.setLayout(new FlowLayout()); Button b1 = new Button("++"); // Button b1.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Flexible.action1(); monitorState(); } } ); c.add("a1", b1); Button b2 = new Button("--"); // Button b2.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { Flexible.action2(); monitorState(); } } ); c.add("a2", b2); stateDisplay = new Label("waiting"); // text Label c.add("sd", stateDisplay); this.c = c; if(isFrame) { ((Window)c).pack(); ((Window)c).setVisible(true); } //make it visible }//GUI constructor // GUI's typically display something of the state of the computation: public void monitorState() { stateDisplay.setText("s="+Flexible.s); c.repaint(); //repaint is a method of class Component } }//GUI class // L. Allison 2007 http://www.allisons.org/ll/