import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Exec {
public static void main(String[] args) {
JFrame jf = new JFrame("My Window");
jf.setLocation(100, 200);
jf.setVisible(true);
BorderLayout fl = new BorderLayout();
jf.setLayout(fl);
JTextField jtf = new JTextField();
jtf.setHorizontalAlignment(JTextField.RIGHT);
JPanel jp = new JPanel();
jf.add(jtf, BorderLayout.NORTH);
jf.add(jp, BorderLayout.CENTER);
jp.setLayout(new GridLayout(4, 3));
EHandling e = new EHandling(jtf);
JButton[] array = new JButton[10];
for (int i = 0; i < array.length; i++) {
array[i] = new JButton();
array[i].setText(String.valueOf(i));
jp.add(array[i]);
array[i].addActionListener(e);
}
JButton jb1 = new JButton();
jb1.setText("+");
JButton jb2 = new JButton();
jb2.setText("=");
jp.add(jb1);
jp.add(jb2);
jb1.setBackground(new Color(0, 255, 0));
jb2.setBackground(Color.YELLOW);
jf.pack();
jb1.addActionListener(e);
jb2.addActionListener(e);
}
}
class EHandling implements ActionListener {
JTextField jtf = null;
int num1 = 0;
public EHandling(JTextField jtf) {
this.jtf = jtf;
}
public void actionPerformed(ActionEvent arg0) {
JButton be = (JButton) arg0.getSource();
if (be.getText().equals("+")) {
num1 = Integer.parseInt(jtf.getText());
jtf.setText("");
} else if (be.getText().equals("=")) {
int num2 = Integer.parseInt(jtf.getText());
jtf.setText(String.valueOf(num1 + num2));
} else {
jtf.setText(jtf.getText() + be.getText());
}
}
}