Text Field Quiz - Java Swing

Java examples for Swing:JTextField

Introduction

Create a calculator that adds or subtracts the contents of two text fields whenever the appropriate button is clicked.

Displaying the result as a label.

Demo Code

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Main extends JFrame implements ActionListener {
  JTextField one = new JTextField("0", 5);
  JButton plusOrMinus = new JButton("+");
  JTextField two = new JTextField("0", 5);
  JButton equals = new JButton("=");
  JLabel result = new JLabel("");

  public Main() {
    super("Add or Subtract Two Numbers");
    setSize(400, 90);/*www.jav a  2 s  .co  m*/
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    FlowLayout flow = new FlowLayout();
    setLayout(flow);
    plusOrMinus.addActionListener(this);
    equals.addActionListener(this);
    add(one);
    add(plusOrMinus);
    add(two);
    add(equals);
    add(result);
    setVisible(true);
  }

  public void actionPerformed(ActionEvent evt) {
    if (evt.getSource() == equals) {
      try {
        int value1 = Integer.parseInt(one.getText());
        int value2 = Integer.parseInt(two.getText());
        if (plusOrMinus.getText().equals("+")) {
          result.setText("" + (value1 + value2));
        } else {
          result.setText("" + (value1 - value2));
        }
      } catch (NumberFormatException exc) {
        one.setText("0");
        two.setText("0");
        result.setText("0");
      }
    }
    if (evt.getSource() == plusOrMinus) {
      if (plusOrMinus.getText().equals("+")) {
        plusOrMinus.setText("-");
      } else {
        plusOrMinus.setText("+");
      }
    }
  }
  public static void main(String[] arguments) {
    Main frame = new Main();
  }
}

Related Tutorials