/* * Joe Schmoe * buttonTest.java * Same as IOpractice.java, but adds a button to submit input. */ import java.applet.Applet; import java.awt.*; // abstract window toolkit (awt) import java.awt.event.*; // for event handlers import javax.swing.*; // swing toolkit public class buttonTest extends JApplet { JButton myButton = new JButton ("Submit"); // create a button JTextField lastField = new JTextField (); // space for last name JTextField firstField = new JTextField (); // space for first name JTextField quantField = new JTextField (); // space for quantity String lastName, firstName; // store names String quantity; // quantity input double total; // computed total double quantVal; // converted quantity // display test average public void paint (Graphics grafObj) { Color myColor = new Color (255, 200, 200); setBackground (myColor); grafObj.clearRect(0, 0, 400, 400); // clear previous text Font myFont = new Font ("Helvetica", Font.PLAIN, 18); grafObj.setFont (myFont); if (quantVal > 0) { grafObj.drawString ("Your cost for "+quantity+" items is: "+total, 10, 140); grafObj.drawString ("Shipping to: "+ lastName +", "+firstName, 10, 160); } } // set up the test GUI public void init () { Container myContainer; // create a panel and objects to put into panel Panel thePanel = new Panel(); JLabel label1 = new JLabel ("Last name: "); JLabel label2 = new JLabel ("First name: "); JLabel label3 = new JLabel ("Quantity: "); // set up how panel will look thePanel.setLayout (new GridLayout (4, 2)); thePanel.setBackground (Color.magenta); // put stuff onto panel thePanel.add (label1); thePanel.add (lastField); thePanel.add (label2); thePanel.add (firstField); thePanel.add (label3); thePanel.add (quantField); // add the button thePanel.add (myButton); // set up the button myButton.addActionListener (new doSubmit()); // add the panel itself to the container myContainer = getContentPane(); myContainer.add (thePanel, BorderLayout.NORTH); quantVal = 0; } // define action when button is pressed public class doSubmit implements ActionListener { public void actionPerformed (ActionEvent event) { // get data from form lastName = lastField.getText(); firstName = firstField.getText(); quantity = quantField.getText(); // convert string to double quantity quantVal = Double.valueOf (quantity).doubleValue(); // calculate average total = 10.99 * quantVal; repaint(); } } }