/** * Example 4-2: Using an MVCTextField with a float * * This example shows how you can use a float as a model behind * an MVCTextField. * * This is the second iteration. It shows using a ValueHolder as the * model and setting the type of the MVCTextField. */ import java.awt.*; import java.util.*; import com.bdnm.mvc.*; public class Example4_2 extends java.applet.Applet implements Observer { /** * This is the model behind the text field we'll create. */ ValueModel 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")); // *** CHANGED *** // Instead of having to understand what a PrintConverter is, // consumers of MVCTextField can just set a type. field.setType(MVCTextField.TYPE_FLOAT); // Get a hold of the model behind the text field model = field.getModel(); // Set up an initial value. Note how we have to convert from // our float to a Float object. This is because ValueModels // deal only with Objects, and a float is not considered an // Object by Java. We'll see a way around this in the third // iteration. model.setValue(new Float(Math.PI)); // 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) { model.setValue(new Float(Math.random())); return true; } return false; } /** * My model changed. Display two times the new value. */ public void update(Observable o, Object arg) { // First thing we have to do is get the new float. Note all // the ugliness we have to go through - this will be addressed // in the third iteration. float newValue = ((Float) model.getValue()).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-2"); Example4_2 applet = new Example4_2(); applet.init(); f.add("Center", applet); f.pack(); f.resize(f.preferredSize()); f.show(); } }