JAVA JFrame을 사용한 간단한 사칙연산


textField1 과 textField2의 숫자를 입력하고 버튼을 누르면 textField3에 답이 나온다.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class MyClass extends JFrame{
    
    JTextField[] jTextField = new JTextField[3];
    JButton[] jb = new JButton[5];
    
    int i;
    int location = 50;
    
    public MyClass(){
        
        setTitle("JTextfiled");
        setSize(500,500);
        setVisible(true);
        
        JPanel panel = new JPanel();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel.setLayout(null);
        add(panel);
        
        for(i = 0; i<jTextField.length; i++){
            jTextField[i] = new JTextField();
            jTextField[i].setBounds(location, 1008030);
            
            location += 100;
            panel.add(jTextField[i]);
        }
        
        location = 50;
        
        for(i = 0; i<jb.length;i++){
            jb[i] = new JButton(" ");
            jb[i].setBounds(location, 3005030);
            
            jb[i].addActionListener(new MyListen());
            
            location += 50;
            panel.add(jb[i]);
        }
        
        jb[0].setText("+");
        jb[1].setText("-");
        jb[2].setText("*");
        jb[3].setText("/");
        jb[4].setText("%");
    }
    
    public static void main(String args[]){
        new MyClass();
    }
    
    class MyListen implements ActionListener{
        
        double temp;
        
        public void actionPerformed(ActionEvent e){
            
            DecimalFormat df = new DecimalFormat("0.###");
            
            double a = Double.parseDouble(jTextField[0].getText());
            double b = Double.parseDouble(jTextField[1].getText());
            
            if(e.getSource() == jb[0]){
                temp = a + b);
            }
            if(e.getSource() == jb[1]){
                temp = a - b;
            }
            if(e.getSource() == jb[2]){
                temp = a * b;
            }
            if(e.getSource() == jb[3]){
                temp = a / b;
            }
            if(e.getSource() == jb[4]){
                temp = a % b;
            }
                //jTextField[2].setText(Double.toString(temp));
                jTextField[2].setText(df.format(temp));
        }
        
    }
}
cs

댓글