/* JApplet1.java CIS 160 David Klick 2011-04-20 Demonstrates a simple JApplet with two text boxes used for input, a label for output, and one button used to make the applet work. */ /* */ import java.awt.Container; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class JApplet1 extends JApplet { JTextField txt1, txt2; JLabel lblOut; public void init() { // get containers set up Container c = getContentPane(); JPanel pnlTop = new JPanel(); JPanel pnlBottom = new JPanel(); // set up layout managers c.setLayout(new GridLayout(2,1)); pnlTop.setLayout(new GridLayout(1,3)); pnlBottom.setLayout(new FlowLayout()); // create components txt1 = new JTextField(); txt2 = new JTextField(); lblOut = new JLabel(); JButton btnAdd = new JButton("Add Numbers"); // place components in containers pnlTop.add(txt1); pnlTop.add(txt2); pnlTop.add(lblOut); pnlBottom.add(btnAdd); // nest containers to get full layout c.add(pnlTop); c.add(pnlBottom); // add ActionListener to make add button work btnAdd.addActionListener(new AddListener()); } public void start() {} public void paint(Graphics g) { super.paint(g); } public void stop() {} public void destroy() {} class AddListener implements ActionListener { public void actionPerformed(ActionEvent e) { double num1=0.0, num2=0.0, tot=0.0; try { num1 = Double.parseDouble(txt1.getText()); num2 = Double.parseDouble(txt2.getText()); tot = num1 + num2; lblOut.setText("" + tot); } catch (NumberFormatException nfe) { lblOut.setText("Error"); } } } }