/** * Example 4-3: Using an MVCTextField with a float * * This example shows how you can use a float as a model behind * an MVCTextField. * * This is the third iteration. It shows using a NumberValueHolder as the * model and setting the type of the MVCTextField. */ import java.awt.*; import java.util.*; import com.bdnm.mvc.*; public class Example4_3 extends java.applet.Applet implements Observer { /** * *** CHANGED *** * This is the ValueModel that we are going to give the text field */ NumberValueHolder model; /** * This is the only method we really need. It is * called when the applet is starting up. This is * where we layout the panel. */ public void init() { // Just give the examples a distinctive background setBackground(new Color(128,128,192)); // First, create the widget, providing the number of // columns just like a TextField. MVCTextField field = new MVCTextField(15); add(field); // Also add the "New Value" button add(new Button("New Value")); // Instead of having to understand what a PrintConverter is, // consumers of MVCTextField can just set a type. field.setType(MVCTextField.TYPE_FLOAT); // *** CHANGED *** // Instead of just using the default ValueHolder that comes // with the MVCTextField, we're going to set a special one // that is more convenient for dealing with numbers. Note how // we can give an initial value right away that is a base type, // not an Object. model = new NumberValueHolder(Math.PI); field.setModel(model); // Finally, become an Observer of the model, so our update() // method gets called whenever it changes. model.addObserver(this); } /** * If the button is pressed, give the model a new float */ public boolean action(Event evt, Object what) { if (evt.target instanceof Button) { // *** CHANGED *** // Note how we are setting a base type, not an Object. // Much more convenient! model.setValue(Math.random()); return true; } return false; } /** * My model changed. Display two times the new value. */ public void update(Observable o, Object arg) { // *** CHANGED *** // Instead of doing that wierd cast stuff, just ask for // the floatValue. float newValue = model.floatValue(); // Now just display two times the new value displayText("Two times the new value is " + 2.0*newValue); } /** * I have something I want to say to the user. Put it both on * the console and the status bar. */ private void displayText(String text) { System.out.println(text); try { showStatus(text); } catch (NullPointerException e) ; } /** * This is just a method to make this run standalone. */ public static void main(String args[]) { Frame f = new Frame("Example 4-3"); Example4_3 applet = new Example4_3(); applet.init(); f.add("Center", applet); f.pack(); f.resize(f.preferredSize()); f.show(); } }