Prev
Next

Turn Java Applets on!

Model/View/Controller:


Decoupling GUIs from data
 1 import java.awt. *;
 2 import java.awt.event. *;
 3 import java.applet.Applet;
 4 
 5 
 6 public class Select extends Applet implements ItemListener {
 7 
 8     
 9     String [] drugs = {"Amitriptyline", "Prozac", "Wellbutrin", 
10 		       "Desipramine", "Crack"};
11 
12     String [] religions = {"Java", "Perl", "C++", "Scheme", "Unlambda"};
13 
14     Choice choice;
15     Button switcher;
16     Label label;
17     boolean which = false;
18     public void init () {
19 
20 	setLayout (new GridLayout (1, 3));
21 	choice = new Choice ();
22 	initChoice ();
23 	add (choice);
24 	choice.addItemListener (this);
25 
26 	switcher = new Button ("Switch");
27 	add (switcher);
28 	switcher.addActionListener (new ActionListener () {
29 		public void actionPerformed (ActionEvent e) {
30 		    which = !which;
31 		    initChoice ();
32 		    changeLabel ();
33 		}
34 	    });
35 
36 	label = new Label ("Nothing ... yet");
37 	add (label);
38     }
39 
40     public void itemStateChanged (ItemEvent e) {
41 	changeLabel ();
42     }
43 
44     void changeLabel () {
45 	String item = (which ? "drug: " : "religion: ") + choice.getSelectedItem ();
46 	if (choice.getSelectedIndex () == 4) 
47 	    if (which) {
48 		item += ". It does a body good!";
49 	    } else {
50 		item += ". `ks``s`k`s`kr``s`k`sikk";
51 	    }
52 	label.setText (item );
53     }
54 
55     void initChoice () {
56 	choice.removeAll();
57 	String [] items = which ? drugs : religions;
58 	for (int i = 0; i < items.length; i ++) {
59 	    choice.addItem (items [i]);
60 	}
61 
62     }
63 }


Prev
Next