자바 이벤트, 간단한 계산기 연습, 메세지 다이얼로그
package test;
import java.awt.Container;
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 Test6 extends JFrame {
JTextField tf1 = new JTextField(10);
JTextField tf2 = new JTextField(10);
JTextField tfResult = new JTextField(10);
JButton btnAdd = new JButton("덧셈");
JButton btnSubtract = new JButton("뺄셈");
JButton btnMultiply = new JButton("곱셈");
JButton btnDivide = new JButton("나눗셈");
public Test6() {
setTitle("간단한 계산기 연습");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(new JLabel("숫자1 : "));
c.add(tf1);
c.add(new JLabel("숫자2 : "));
c.add(tf2);
c.add(btnAdd);
c.add(btnSubtract);
c.add(btnMultiply);
c.add(btnDivide);
c.add(tfResult);
btnAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String strNum1 = tf1.getText().trim();
String strNum2 = tf2.getText().trim();
int num1 = Integer.parseInt(strNum1);
int num2 = Integer.parseInt(strNum2);
int sum = num1 + num2;
tfResult.setText(Integer.toString(sum));
}
});
btnSubtract.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String strNum1 = tf1.getText().trim();
String strNum2 = tf2.getText().trim();
int num1 = Integer.parseInt(strNum1);
int num2 = Integer.parseInt(strNum2);
int sum = num1 - num2;
tfResult.setText(Integer.toString(sum));
}
});
btnMultiply.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String strNum1 = tf1.getText().trim();
String strNum2 = tf2.getText().trim();
int num1 = Integer.parseInt(strNum1);
int num2 = Integer.parseInt(strNum2);
int sum = num1 * num2;
tfResult.setText(Integer.toString(sum));
}
});
btnDivide.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String strNum1 = tf1.getText().trim();
String strNum2 = tf2.getText().trim();
int num1 = Integer.parseInt(strNum1);
int num2 = Integer.parseInt(strNum2);
int sum = num1 / num2;
tfResult.setText(Integer.toString(sum));
}
});
setSize(220, 250);
setVisible(true);
}
public static void main(String[] args) {
new Test6();
}
}