Adding Two Numbers in a Java Swing GUI

Adding GUI

/**
 * Last Friday I was approached in my office by our
 * CS Department's Head Lab Assistant and the TA
 * responsible for teaching our Java 3 course.
 *
 * The Head Lab Assistant told me that the TA (standing
 * right beside her) was sick and unable to teach.
 * Someone needed to fill in the course for him.
 * I'm the fall back up guy for these kinds of emergencies,
 * so it fell to me to teach this guy's class that was
 * in just 1 hour and 30 minutes. The topic was
 * "Java GUI Programming". There was no material prepared.
 *
 * So I did what any red-blooded American would do:
 * I went to lunch.
 *
 * After my lunch break, I started working on two programs
 * that could be used as a lab project that could
 * possibly fill the 2 hour lab.
 *
 * The Head Lab Assistant had already prepared my handouts
 * for the class. All I had to do was teach. Schweet.
 *
 * This program creates a GUI window with two text boxes
 * and a button. You can enter two numbers into the box,
 * click the button, and it will print the sum on the screen.
 *
 * Of the two lab projects, this was the harder one. The
 * easier program was a random number generator.
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AddingGui extends JFrame {

    private JPanel myPanel;
    private JButton addButton;
    private JLabel instructionsLabel;
    private JLabel sumLabel;
    private JTextField firstBox;
    private JTextField secondBox;

    public AddingGui() {

        instructionsLabel = new JLabel("Enter a value into each box and click 'Add'.");
        sumLabel = new JLabel("");
        addButton = new JButton("Add");
        firstBox = new JTextField(5);
        secondBox = new JTextField(5);

        ButtonListener listener = new ButtonListener();
        addButton.addActionListener(listener);

        myPanel = new JPanel();
        myPanel.setPreferredSize( new Dimension(400, 200) );
        myPanel.add(instructionsLabel);
        myPanel.add(firstBox);
        myPanel.add(secondBox);
        myPanel.add(addButton);
        myPanel.add(sumLabel);

        add( myPanel, BorderLayout.CENTER );
    }

    private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == addButton) {
                int firstNum = Integer.parseInt(firstBox.getText());
                int secondNum = Integer.parseInt(secondBox.getText());
                sumLabel.setText( Integer.toString( firstNum + secondNum ) );
            }
        }
    }

    public static void main(String[] args) {
        AddingGui gui = new AddingGui();
        gui.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        gui.setSize(200,200);
        gui.setVisible(true);
    }
}
  1. sp0rus reblogged this from jcchurch and added:
    I was in this class. I completed the assignment. King of the lab!
  2. jcchurch posted this