import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class JavaGUI extends JFrame{
String names[] = {"1", "2", "3" ,"+" , "4", "5", "6", "-", "7", "8", "9", "*", "C", "0", "=", "/"};
JTextField inputText;
JButton buttons[];
JavaGUI(){
setSize(300, 400);
setTitle("계산기");
setLayout(new BorderLayout(0, 10));
JPanel inputPanel = new JPanel(new BorderLayout(5, 2));
JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
add(inputPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
inputText = new JTextField();
inputText.setHorizontalAlignment(JTextField.RIGHT);
inputPanel.add(inputText);
buttons = new JButton[16];
for(int i = 0; i< 16; i++){
buttons[i] = new JButton(names[i]);
buttonPanel.add(buttons[i]);
}
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class Calculator extends JavaGUI implements ActionListener{
Calculator(){
for(int i = 0; i< 16; i++){
buttons[i].addActionListener(this);
}
}
@Override
public void actionPerformed(ActionEvent e) {
JButton pressedButton = (JButton)e.getSource();
String text = pressedButton.getText();
switch (text) {
case "=":
int result = textAnalysis(inputText.getText());
inputText.setText("" + result);
break;
case "C":
inputText.setText("");
break;
default:
inputText.setText(inputText.getText() + text);
break;
}
}
int textAnalysis(String text){
if (text.contains("+")){
String[] formula = text.split("\\+");
int x = Integer.parseInt(formula[0]);
int y = Integer.parseInt(formula[1]);
return x + y;
}
if (text.contains("-")){
String[] formula = text.split("-");
int x = Integer.parseInt(formula[0]);
int y = Integer.parseInt(formula[1]);
return x - y;
}
if (text.contains("*")){
String[] formula = text.split("\\*");
int x = Integer.parseInt(formula[0]);
int y = Integer.parseInt(formula[1]);
return x * y;
}
if (text.contains("/")){
String[] formula = text.split("/");
int x = Integer.parseInt(formula[0]);
int y = Integer.parseInt(formula[1]);
return x / y;
}
return 0;
}
}
public class GUI {
public static void main(String[] args) {
System.out.println("시작!");
Calculator gui = new Calculator();
}
}