Enter two numbers in the top two input fields and click a button to compute the result or clear all input/output.

The app source is as follows:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calc
{
public static void main(String[] args)
{
SwingApp app = new SwingApp(250, 150); // set app window size
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class SwingApp extends JFrame implements ActionListener
{
private final DrawPanel panel; // class variable
private final JTextField n1, n2, res;
private final JButton plusB, minusB, timesB, overB, clearB;
public SwingApp(int width, int height) // class constructor
{
super(); // call to super class constructor
Container pane = super.getContentPane(); // create layout, set colors
panel = new DrawPanel(); // add GUI components
panel.setBackground(Color.yellow);
panel.setLayout(new GridLayout(3, 2, 10, 10));
n1 = new JTextField(6); // text fields
n2 = new JTextField();
res = new JTextField();
plusB = new JButton(" + "); // buttons
minusB = new JButton(" - ");
timesB = new JButton(" x ");
overB = new JButton(" / ");
clearB = new JButton(" C ");
JPanel p1 = new JPanel(); // "left" panel
p1.setLayout(new GridLayout(1, 2, 10, 0));
p1.add(plusB);
p1.add(minusB);
JPanel p2 = new JPanel(); // "right" panel
p2.setLayout(new GridLayout(1, 2, 10, 0));
p2.add(timesB);
p2.add(overB);
panel.add(n1);
panel.add(p1);
panel.add(n2);
panel.add(p2);
panel.add(res);
panel.add(clearB);
plusB.addActionListener(this); // set up event listeners
minusB.addActionListener(this);
timesB.addActionListener(this);
overB.addActionListener(this);
clearB.addActionListener(this);
pane.add(panel);
Toolkit toolkit = Toolkit.getDefaultToolkit(); // optionally position JFrame
Dimension screenSize = toolkit.getScreenSize(); // in the middle of the screen
super.setLocation((screenSize.width - width)/2, (screenSize.height - height)/2);
super.setTitle("Swing app"); // set desired window title
super.setSize(width, height); // set desired window size
super.setVisible(true);
// add here more code for GUI components
}
// this method is called if any button is pressed
@Override
public void actionPerformed(ActionEvent e)
{
String s = n1.getText(); // get the numbers from the
double n1 = Double.parseDouble(s); // GUI
s = n2.getText();
double n2 = Double.parseDouble(s);
if (e.getSource() == plusB) // ckeck which button was clicked
res.setText((n1+n2)+""); // compute the result and
else if (e.getSource() == minusB) // display it
res.setText((n1-n2)+"");
else if (e.getSource() == timesB)
res.setText((n1*n2)+"");
else if (e.getSource() == overB)
res.setText((n1/n2)+"");
else if (e.getSource() == clearB) // clear all input fields
{
this.n1.setText("");
this.n2.setText("");
res.setText("");
}
}
}
class DrawPanel extends JPanel // main window panel
{
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g); // must be the 1st line
// add here more code for drawing on panel
}
}
|