package com.calculator;

public class Calculator {

    public int sum(int a, int b) {

        return a+b;

    }

}

 

package com.test;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.calculator.Calculator;

public class CalculatorTest {

    @Test

    public void testSum() {

        Calculator cal=new Calculator();

        assertEquals(30, cal.sum(20, 10));

    }

}

 

 


package com.test;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.calculator.Calculator;

public class CalculatorTest {

    @Test

    public void testSum() {

        Calculator cal=new Calculator();

        assertEquals(30, cal.sum(20, 10));

        System.out.println("test1");

    }

    @Test

    public void testSum1() {

        Calculator cal=new Calculator();

        assertEquals(60, cal.sum(50, 10));

        System.out.println("test2");

    }

}


 

package com.test;

import static org.junit.Assert.assertEquals;

import org.junit.After;

import org.junit.AfterClass;

import org.junit.Before;

import org.junit.BeforeClass;

import org.junit.Test;

import com.calculator.Calculator;

public class CalculatorTest {

    @Test

    public void testSum() {

        Calculator cal=new Calculator();

        assertEquals(30, cal.sum(20, 10));

        System.out.println("test1");

    }

    @Test

    public void testSum1() {

        Calculator cal=new Calculator();

        assertEquals(60, cal.sum(50, 10));

        System.out.println("test2");

    }

    //BeforeClass부터 출력됨

    @BeforeClass

    public static void beforeTest() {

        System.out.println("BeforeClass");

    }

    @Before //단위 테스트 할때마다 부름

    public void setUp() {

        System.out.println("Before setUp");

    }

    @After //단위 테스트 할때마다 부름

    public void tearDown() {

        System.out.println("After tearDown");

    }

    //AfterClass가 제일 마지막에 출력됨

    @AfterClass

    public static void afterTest() {

        System.out.println("AfterClass");

    }

}

 

 


 

 

 

 

처음 자바 스윙으로 시작한 개인프로젝트를 끝냈다.

JDBC를 사용한 영단어 암기 프로그램이다.

비회원은 단어 목록 조회만, 회원은 테스트를 진행, 관리자는 회원 및 단어 관리를 할 수 있게끔 만들었다.

 

https://github.com/kkj0712/Java_Swing_project

 

kkj0712/Java_Swing_project

Contribute to kkj0712/Java_Swing_project development by creating an account on GitHub.

github.com

 

 

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
package swingTest;
//선수 정보 컬럼명 저장.
public class Player {
    private int num;
    private String name;
    private String birth;
    private double height;
    private double weight;
    private String kind;
    
    public int getNum() {
        return num;
    }
    public void setNum(int num) {
        this.num = num;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getBirth() {
        return birth;
    }
    public void setBirth(String birth) {
        this.birth = birth;
    }
    public double getHeight() {
        return height;
    }
    public void setHeight(double height) {
        this.height = height;
    }
    public double getWeight() {
        return weight;
    }
    public void setWeight(double weight) {
        this.weight = weight;
    }
    public String getKind() {
        return kind;
    }
    public void setKind(String kind) {
        this.kind = kind;
    }
}
 
cs

 

 

 

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package swingTest;
 
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
 
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
public class PlayerSwing2 extends JFrame {
    JTextField []tf=new JTextField[6];
    PlayerDBA dao=new PlayerDBA();
    
    public PlayerSwing2() {
        setTitle("Player Test22");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(2,2));
        
        add(new PanelPane()); //1행 1열
        
        JTextArea ta=new JTextArea(); //1행 2열
        JScrollPane jsp=new JScrollPane(ta);
        add(jsp); 
        ta.addMouseListener(new MouseAdapter() { //번호 선택시 상세보기
            public void mouseReleased(MouseEvent e) {
              int num = Integer.parseInt(ta.getSelectedText().trim());
              Player p=dao.playerDetail(num); //rs가 아닌 객체에 담아서 값을 돌림
              tf[0].setText(num+"");
              tf[1].setText(p.getName());
              tf[2].setText(p.getBirth());
              tf[3].setText(p.getHeight()+"");
              tf[4].setText(p.getWeight()+"");
              tf[5].setText(p.getKind());
            }
        });
    
        JPanel p1=new JPanel(); //2행 1열
        JButton insertBtn=new JButton("추가");
        JButton viewBtn=new JButton("보기");
        JButton updateBtn=new JButton("수정");
        JButton deleteBtn=new JButton("삭제");
        p1.add(insertBtn); p1.add(viewBtn); p1.add(updateBtn); p1.add(deleteBtn);
        add(p1); 
        
        //추가 
        insertBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                Player p=new Player();
                p.setName(tf[1].getText());
                p.setBirth(tf[2].getText());
                p.setHeight(Double.parseDouble(tf[3].getText()));
                p.setWeight(Double.parseDouble(tf[4].getText()));
                p.setKind(tf[5].getText());
                dao.playerInsert(p);
                viewBtn.doClick();
            }
        });
 
        
        //보기
        viewBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                ta.setText("");
                ArrayList<Player> arr=dao.playerView();
                for(Player p:arr) { //ArrayList돌면서 ta에 정보 붙여넣기
                    ta.append("번호>> "+p.getNum()+"\n");
                    ta.append("이름>> "+p.getName()+"\n");
                    ta.append("생일>> "+p.getBirth()+"\n");
                    ta.append("키>> "+p.getHeight()+"\n");
                    ta.append("몸무게>> "+p.getWeight()+"\n");
                    ta.append("종목>> "+p.getKind()+"\n");
                    ta.append("\n");
                }
            }
        });
        
        //수정 (ta에서 번호를 선택한 후 tf창에 뜨면 수정)
        updateBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                  Player p= new Player();
                  p.setNum(Integer.parseInt(tf[0].getText()));
                  p.setName(tf[1].getText());
                  p.setBirth(tf[2].getText());
                  p.setHeight(Double.parseDouble(tf[3].getText()));
                  p.setWeight(Double.parseDouble(tf[4].getText()));
                  p.setKind(tf[5].getText());
                  dao.playerUpdate(p); 
                  viewBtn.doClick();
                  clearText();
            }
        });
 
        //삭제
        deleteBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                int num=Integer.parseInt(tf[0].getText()); //tf[0]에 들어있는 글자(숫자)
                dao.playerDelete(num);
                viewBtn.doClick(); //보기버튼 클릭
                clearText(); //내용지우기
            }
        });
        
        JPanel p2=new JPanel(); //2행 2열
        JComboBox<String>jcb=new JComboBox<String>();
        jcb.addItem("이름");
        jcb.addItem("종목");
        JTextField searchtf=new JTextField(10);
        JButton searchBtn=new JButton("검색");
        p2.add(jcb); p2.add(searchtf); p2.add(searchBtn);
        add(p2); 
        
        //검색버튼 (이름, 종목으로 검색)
        searchBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                ta.setText("");
                int idx=jcb.getSelectedIndex(); //콤보박스에서 선택한 값 (이름, 종목 인덱스 0,1)
                String key="";
                if(idx==0) {
                    key="name";
                }else if(idx==1) {
                    key="kind";
                }
                ArrayList<Player>arr=dao.playerSearch(key, searchtf.getText());
                for(Player p:arr) { //ArrayList돌면서 ta에 정보 붙여넣기
                    ta.append("번호>> "+p.getNum()+"\n");
                    ta.append("이름>> "+p.getName()+"\n");
                    ta.append("생일>> "+p.getBirth()+"\n");
                    ta.append("키>> "+p.getHeight()+"\n");
                    ta.append("몸무게>> "+p.getWeight()+"\n");
                    ta.append("종목>> "+p.getKind()+"\n\n");
                }
            }
        });
        
        setSize(600,400);
        setVisible(true);
        
    }
    
    class PanelPane extends JPanel {
        private String[] text= {"번호","이름","생일","키","몸무게","종목"};
        public PanelPane() {
            setLayout(null); //좌표를 내가 정하겠다.
            for(int i=0;i<text.length;i++) {
                JLabel la=new JLabel(text[i]);
                la.setHorizontalAlignment(JLabel.RIGHT);
                la.setSize(50,20);
                la.setLocation(30,50+i*20); //y좌표를 늘여야지 글자가 겹치지 않음
                add(la);
                tf[i]=new JTextField(50);
                tf[i].setHorizontalAlignment(JTextField.CENTER);
                tf[i].setSize(150,20);
                tf[i].setLocation(12050+i*20);
                add(tf[i]);
            }
            tf[0].setEditable(false);
        }
    }
    
    private void clearText() {
        for(int i=0;i<tf.length;i++) {
            tf[i].setText("");
        }
    }
    
    public static void main(String[] args) {
        new PlayerSwing2();
    }
}
cs

 

 

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package swingTest;
//db와 연결
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
 
public class PlayerDBA {
    String url, user, pwd;
    
    //db연결: 생성자가 해줌. url,user,pwd는 앞으로 계속 쓸거라서 전역변수로 빼줌.
    public PlayerDBA() {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            url="jdbc:oracle:thin:@localhost:1521:xe"//1521:오라클이 깔린 포트 번호
            user="scott";
            pwd="1234";
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    
    //추가
    public void playerInsert(Player p) {
        Connection con=null;
        PreparedStatement ps=null;
        
        try {
            con=DriverManager.getConnection(url,user,pwd);
            String sql="INSERT INTO player "
                    + "VALUES (player_seq.nextval,?,?,?,?,?)";
            ps=con.prepareStatement(sql);
            ps.setString(1, p.getName());
            ps.setString(2, p.getBirth());
            ps.setDouble(3, p.getHeight());
            ps.setDouble(4, p.getWeight());
            ps.setString(5, p.getKind());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(con,ps);
        }
        
    }
    
    //상세보기
    public Player playerDetail(int num) {
        Connection con=null;
        Statement st=null;
        ResultSet rs=null;
        Player p=null;
        try {
            con=DriverManager.getConnection(url,user,pwd);
            String sql="SELECT*FROM player WHERE num="+num;
            st=con.createStatement();
            rs=st.executeQuery(sql);
            if(rs.next()) { //rs가 있다면 p에 다 담으면 됨
                p=new Player(); //Player 객체 만들어주고 게터 세터 활용
                p.setNum(rs.getInt("num"));
                p.setName(rs.getString("name"));
                p.setBirth(rs.getString("birth"));
                p.setHeight(rs.getDouble("height"));
                p.setWeight(rs.getDouble("weight"));
                p.setKind(rs.getString("kind"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(con, st, rs);
        } 
        return p;
    }
    
    //보기
    public ArrayList<Player> playerView() { //arr값을 PlayerSwing2에 돌려줘야함. 리턴값은 ArrayList<Player>
        Connection con=null//연결하는 객체들은 나중에 반드시 닫아주기 (닫기 메소드 따로 사용)
        Statement st=null;
        ResultSet rs=null;
        ArrayList<Player> arr=new ArrayList<Player>(); //rs.next()가 도는 동안 저장해야할 곳=ArrayList
        try {
            con=DriverManager.getConnection(url,user,pwd);
            String sql="select * from player order by num desc";
            st=con.createStatement();
            rs=st.executeQuery(sql);
            while(rs.next()) {
                Player p=new Player(); //Player 객체 만들어주고 게터 세터 활용
                p.setNum(rs.getInt("num"));
                p.setName(rs.getString("name"));
                p.setBirth(rs.getString("birth"));
                p.setHeight(rs.getDouble("height"));
                p.setWeight(rs.getDouble("weight"));
                p.setKind(rs.getString("kind"));
                arr.add(p);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally { //try, catch문 수행하든 반드시 실행. 닫기 메소드 호출
            closeConnection(con,st,rs);
        }
        return arr;
    }
    
    //수정
    public void playerUpdate(Player p) {
        Connection con=null;
        PreparedStatement ps=null;
        try {
            String sql="UPDATE player SET name=?, birth=?, "
                    + "height=?, weight=?,kind=? where num=?";
            con=DriverManager.getConnection(url,user,pwd);
            ps=con.prepareStatement(sql);
                ps.setString(1, p.getName());
                ps.setString(2, p.getBirth());
                ps.setDouble(3, p.getHeight());
                ps.setDouble(4, p.getWeight());
                ps.setString(5, p.getKind());
                ps.setInt(6, p.getNum());
                ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(con, ps);
        } 
    }
    
    //삭제
    public void playerDelete(int num) {
        Connection con=null;
        Statement st=null;
        try {
            con=DriverManager.getConnection(url,user,pwd);
            String sql="DELETE FROM palyer WHERE num="+num;
            st=con.createStatement();
            st.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(con, st, null);
        }
    }
    
    //검색
    public ArrayList<Player> playerSearch(String key, String word) {
        Connection con=null;
        Statement st=null;
        ResultSet rs=null;
        ArrayList<Player>arr=new ArrayList<Player>(); //전체보기와 똑같은데 sql문만 다름
        try {
            con=DriverManager.getConnection(url,user,pwd);
            st=con.createStatement();
            String sql="SELECT * FROM player WHERE "
                    +key+" LIKE '%"+word+"%'";
            rs=st.executeQuery(sql);
            while(rs.next()) {
                Player p=new Player(); 
                p.setNum(rs.getInt("num"));
                p.setName(rs.getString("name"));
                p.setBirth(rs.getString("birth"));
                p.setHeight(rs.getDouble("height"));
                p.setWeight(rs.getDouble("weight"));
                p.setKind(rs.getString("kind"));
                arr.add(p);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(con, st, rs);
        }
        return arr;
    }
    
    //닫기 (종료)메소드
    public void closeConnection(Connection con, Statement st, ResultSet rs) {
        try {
            if(rs!=null) rs.close();
            if(st!=null) st.close();
            if(con!=null) con.close();
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
    
    public void closeConnection(Connection con, PreparedStatement ps) {
        try {
            if(con!=null) con.close();
            if(ps!=null) ps.close();
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
}
cs

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package swingTest;
 
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
public class PlayerSwing extends JFrame {
    JTextField []tf=new JTextField[6];
    Connection con;
    
    public PlayerSwing() {
        dbCon(); //db연결
        setTitle("Player Test");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(2,2));
        
        add(new PanelPane()); //1행 1열
        
        JTextArea ta=new JTextArea(); //1행 2열
        JScrollPane jsp=new JScrollPane(ta);
        add(jsp); 
        ta.addMouseListener(new MouseAdapter() { //인터페이스를 구현한 클래스=Adapter
            public void mouseReleased(MouseEvent e) {
              try {
                int num = Integer.parseInt(ta.getSelectedText().trim()); //선택한 num
                tf[0].setText(num+"");
                String sql="SELECT*FROM player WHERE num="+num;
                Statement st=con.createStatement();
                ResultSet rs=st.executeQuery(sql);
                if(rs.next()) {
                    tf[1].setText(rs.getString("name"));
                    tf[2].setText(rs.getString("birth"));
                    tf[3].setText(rs.getDouble("height")+"");
                    tf[4].setText(rs.getDouble("weight")+"");
                    tf[5].setText(rs.getString("kind"));
                }
              }catch(NullPointerException n) {
                JOptionPane.showMessageDialog(null"번호를 선택하세요");
              }catch(NumberFormatException n2) {
                JOptionPane.showMessageDialog(null"번호를 선택하세요");
              }catch(SQLException e1) {
                e1.printStackTrace();
              }
            }
        });
    
        
        JPanel p1=new JPanel(); //2행 1열
        JButton insertBtn=new JButton("추가");
        JButton viewBtn=new JButton("보기");
        JButton updateBtn=new JButton("수정");
        JButton deleteBtn=new JButton("삭제");
        p1.add(insertBtn); p1.add(viewBtn); p1.add(updateBtn); p1.add(deleteBtn);
        add(p1); 
        
        //추가 
        insertBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                String sql="INSERT INTO player "
                        + "VALUES (player_seq.nextval,?,?,?,?,?)";
                try {
                    PreparedStatement ps=con.prepareStatement(sql);
                    ps.setString(1, tf[1].getText());
                    ps.setString(2, tf[2].getText());
                    ps.setDouble(3, Double.parseDouble(tf[3].getText()));
                    ps.setDouble(4, Double.parseDouble(tf[4].getText()));
                    ps.setString(5, tf[5].getText());
                    ps.executeUpdate();
                    clearText();
                    viewBtn.doClick(); //보기 버튼 안눌러도 됨
                } catch (SQLException e1) {
                    e1.printStackTrace();
                } catch (NumberFormatException n1) {
                    n1.printStackTrace();
                    JOptionPane.showMessageDialog(null"번호를 입력하세요");
                }
            }
        });
 
        
        //보기
        viewBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                ta.setText("");
                String sql="SELECT * FROM player order by num desc";
                try {
                Statement st=con.createStatement();
                ResultSet rs=st.executeQuery(sql);
                while(rs.next()) {
                    ta.append("번호: "+rs.getInt("num")+"\n");
                    ta.append("이름: "+rs.getString("name")+"\n");
                    ta.append("생일: "+rs.getString("birth")+"\n");
                    ta.append("키: "+rs.getDouble("height")+"\n");
                    ta.append("몸무게: "+rs.getDouble("weight")+"\n");
                    ta.append("종목: "+rs.getString("kind")+"\n");
                    ta.append("\n");
                }
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                
            }
        });
        
        //수정
        updateBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                String sql="UPDATE player SET name=?, birth=?, "
                        + "height=?, weight=?,kind=? where num=?";
                try {
                    PreparedStatement ps=con.prepareStatement(sql);
                    ps.setString(1, tf[1].getText());
                    ps.setString(2, tf[2].getText());
                    ps.setDouble(3, Double.parseDouble(tf[3].getText()));
                    ps.setDouble(4, Double.parseDouble(tf[4].getText()));
                    ps.setString(5, tf[5].getText());
                    ps.setInt(6, Integer.parseInt(tf[0].getText()));
                    ps.executeUpdate();
                    clearText();
                    viewBtn.doClick();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        });
 
        //삭제
        deleteBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                int result=JOptionPane.showConfirmDialog(null"정말 삭제할까요?",
                        "Confirm",JOptionPane.YES_NO_OPTION);
                if(JOptionPane.YES_OPTION==result) { //삭제
                    int num=Integer.parseInt(tf[0].getText());
                    try {
                        String sql="DELETE FROM player where num="+num;
                        Statement st=con.createStatement(); //num이 아니라 name등 String 형이었으면 prestatement쓰는게 더 간단
                        st.executeUpdate(sql);
                        clearText(); 
                        viewBtn.doClick();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        });
        
        JPanel p2=new JPanel(); //2행 2열
        JComboBox<String>jcb=new JComboBox<String>();
        jcb.addItem("이름");
        jcb.addItem("종목");
        JTextField searchtf=new JTextField(10);
        JButton searchBtn=new JButton("검색");
        p2.add(jcb); p2.add(searchtf); p2.add(searchBtn);
        add(p2); 
        
        //검색버튼 (이름, 종목으로 검색)
        searchBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                ta.setText(""); //일단 비워주기 
                int idx=jcb.getSelectedIndex(); //콤보박스에서 선택한 값 (이름, 종목 인덱스 0,1)
                String key="";
                if(idx==0) {
                    key="name";
                }else if(idx==1) {
                    key="kind";
                }
                
                String sql="SELECT * FROM player WHERE "
                        +key+" LIKE '%"+searchtf.getText()+"%'"
                //where뒤, like전에 반드시 띄우기. searchtf에 쓴 게 sql에 있는지 확인
                try {
                    Statement st=con.createStatement();//물음표 없으니 statement
                    ResultSet rs=st.executeQuery(sql);
                    while(rs.next()) {
                        ta.append("번호: "+rs.getInt("num")+"\n");
                        ta.append("이름: "+rs.getString("name")+"\n");
                        ta.append("생일: "+rs.getString("birth")+"\n");
                        ta.append("키: "+rs.getDouble("height")+"\n");
                        ta.append("몸무게: "+rs.getDouble("weight")+"\n");
                        ta.append("종목: "+rs.getString("kind")+"\n");
                        ta.append("\n");
                    }
                } catch (SQLException e1) {
                    e1.printStackTrace();
                } 
            }
        });
        
        setSize(600,400);
        setVisible(true);
        
    }
    
    class PanelPane extends JPanel {
        private String[] text= {"번호","이름","생일","키","몸무게","종목"};
        public PanelPane() {
            setLayout(null); //좌표를 내가 정하겠다.
            for(int i=0;i<text.length;i++) {
                JLabel la=new JLabel(text[i]);
                la.setHorizontalAlignment(JLabel.RIGHT);
                la.setSize(50,20);
                la.setLocation(30,50+i*20); //y좌표를 늘여야지 글자가 겹치지 않음
                add(la);
                tf[i]=new JTextField(50);
                tf[i].setHorizontalAlignment(JTextField.CENTER);
                tf[i].setSize(150,20);
                tf[i].setLocation(12050+i*20);
                add(tf[i]);
            }
            tf[0].setEditable(false);
        }
    }
    
    //디비연결
    private void dbCon() {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            String url="jdbc:oracle:thin:@localhost:1521:xe"//1521:오라클이 깔린 포트 번호
            String user="scott";
            String pwd="1234";
            con=DriverManager.getConnection(url,user,pwd);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException s) {
            s.printStackTrace();
        }
    }
    
    private void clearText() {
        for(int i=0;i<tf.length;i++) {
            tf[i].setText("");
        }
    }
    
    public static void main(String[] args) {
        new PlayerSwing();
    }
}
 
cs
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package swingTest;
 
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
public class PlayerSwing extends JFrame {
    JTextField []tf=new JTextField[6];
    Connection con;
    
    public PlayerSwing() {
        dbCon(); //db연결
        setTitle("Player Test");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(2,2));
        
        add(new PanelPane()); //1행 1열
        
        JTextArea ta=new JTextArea(); //1행 2열
        JScrollPane jsp=new JScrollPane(ta);
        add(jsp); 
        ta.addMouseListener(new MouseAdapter() { //인터페이스를 구현한 클래스=Adapter
            public void mouseReleased(MouseEvent e) {
              try {
                int num = Integer.parseInt(ta.getSelectedText().trim()); //선택한 num
                tf[0].setText(num+"");
                String sql="SELECT*FROM player WHERE num="+num;
                Statement st=con.createStatement();
                ResultSet rs=st.executeQuery(sql);
                if(rs.next()) {
                    tf[1].setText(rs.getString("name"));
                    tf[2].setText(rs.getString("birth"));
                    tf[3].setText(rs.getDouble("height")+"");
                    tf[4].setText(rs.getDouble("weight")+"");
                    tf[5].setText(rs.getString("kind"));
                }
              }catch(NullPointerException n) {
                JOptionPane.showMessageDialog(null"번호를 선택하세요");
              }catch(NumberFormatException n2) {
                JOptionPane.showMessageDialog(null"번호를 선택하세요");
              }catch(SQLException e1) {
                e1.printStackTrace();
              }
            }
        });
    
        
        JPanel p1=new JPanel(); //2행 1열
        JButton insertBtn=new JButton("추가");
        JButton viewBtn=new JButton("보기");
        JButton updateBtn=new JButton("수정");
        JButton deleteBtn=new JButton("삭제");
        p1.add(insertBtn); p1.add(viewBtn); p1.add(updateBtn); p1.add(deleteBtn);
        add(p1); 
        
        //추가 
        insertBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                String sql="INSERT INTO player "
                        + "VALUES (player_seq.nextval,?,?,?,?,?)";
                try {
                    PreparedStatement ps=con.prepareStatement(sql);
                    ps.setString(1, tf[1].getText());
                    ps.setString(2, tf[2].getText());
                    ps.setDouble(3, Double.parseDouble(tf[3].getText()));
                    ps.setDouble(4, Double.parseDouble(tf[4].getText()));
                    ps.setString(5, tf[5].getText());
                    ps.executeUpdate();
                    clearText();
                    viewBtn.doClick(); //보기 버튼 안눌러도 됨
                } catch (SQLException e1) {
                    e1.printStackTrace();
                } catch (NumberFormatException n1) {
                    n1.printStackTrace();
                }
            }
        });
 
        
        //보기
        viewBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                ta.setText("");
                String sql="SELECT * FROM player order by num desc";
                try {
                Statement st=con.createStatement();
                ResultSet rs=st.executeQuery(sql);
                while(rs.next()) {
                    ta.append("번호: "+rs.getInt("num")+"\n");
                    ta.append("이름: "+rs.getString("name")+"\n");
                    ta.append("생일: "+rs.getString("birth")+"\n");
                    ta.append("키: "+rs.getDouble("height")+"\n");
                    ta.append("몸무게: "+rs.getDouble("weight")+"\n");
                    ta.append("종목: "+rs.getString("kind")+"\n");
                    ta.append("\n");
                }
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                
            }
        });
        
        //수정
        updateBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                String sql="UPDATE player SET name=?, birth=?, "
                        + "height=?, weight=?,kind=? where num=?";
                try {
                    PreparedStatement ps=con.prepareStatement(sql);
                    ps.setString(1, tf[1].getText());
                    ps.setString(2, tf[2].getText());
                    ps.setDouble(3, Double.parseDouble(tf[3].getText()));
                    ps.setDouble(4, Double.parseDouble(tf[4].getText()));
                    ps.setString(5, tf[5].getText());
                    ps.setInt(6, Integer.parseInt(tf[0].getText()));
                    ps.executeUpdate();
                    clearText();
                    viewBtn.doClick();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        });
 
        //삭제
        deleteBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                int result=JOptionPane.showConfirmDialog(null"정말 삭제할까요?",
                        "Confirm",JOptionPane.YES_NO_OPTION);
                if(JOptionPane.YES_OPTION==result) { //삭제
                    int num=Integer.parseInt(tf[0].getText());
                    try {
                        String sql="DELETE FROM player where num="+num;
                        Statement st=con.createStatement();
                        st.executeUpdate(sql);
                        clearText(); 
                        viewBtn.doClick();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        });
        
        JPanel p2=new JPanel(); //2행 2열
        JComboBox<String>jcb=new JComboBox<String>();
        jcb.addItem("이름");
        jcb.addItem("종목");
        JTextField searchtf=new JTextField(10);
        JButton searchBtn=new JButton("검색");
        p2.add(jcb); p2.add(searchtf); p2.add(searchBtn);
        add(p2); 
        
        //검색버튼
        searchBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                
            }
        });
        
        setSize(600,400);
        setVisible(true);
        
    }
    
    class PanelPane extends JPanel {
        private String[] text= {"번호","이름","생일","키","몸무게","종목"};
        public PanelPane() {
            setLayout(null); //좌표를 내가 정하겠다.
            for(int i=0;i<text.length;i++) {
                JLabel la=new JLabel(text[i]);
                la.setHorizontalAlignment(JLabel.RIGHT);
                la.setSize(50,20);
                la.setLocation(30,50+i*20); //y좌표를 늘여야지 글자가 겹치지 않음
                add(la);
                tf[i]=new JTextField(50);
                tf[i].setHorizontalAlignment(JTextField.CENTER);
                tf[i].setSize(150,20);
                tf[i].setLocation(12050+i*20);
                add(tf[i]);
            }
            tf[0].setEditable(false);
        }
    }
    
    //디비연결
    private void dbCon() {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            String url="jdbc:oracle:thin:@localhost:1521:xe"//1521:오라클이 깔린 포트 번호
            String user="scott";
            String pwd="1234";
            con=DriverManager.getConnection(url,user,pwd);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException s) {
            s.printStackTrace();
        }
    }
    
    private void clearText() {
        for(int i=0;i<tf.length;i++) {
            tf[i].setText("");
        }
    }
    
    public static void main(String[] args) {
        new PlayerSwing();
    }
}
 
cs

 

 

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package swingTest;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringWriter;
 
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
 
public class Memo extends JFrame{
    JTextArea ta;
    File f;
    public Memo(String title) {
        setTitle(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JMenu mfile=new JMenu("파일");
        
        JMenuItem mOpen=new JMenuItem("열기");
        JMenuItem mNew=new JMenuItem("새파일");
        JMenuItem mSave=new JMenuItem("저장");
        JMenuItem mSaveAs=new JMenuItem("다른이름으로 저장");
        JMenuItem mExit=new JMenuItem("끝내기");
        
        mfile.add(mOpen);
        mfile.add(mNew);
        mfile.add(mSave);
        mfile.add(mSaveAs);
        mfile.addSeparator();
        mfile.add(mExit);
        
        JMenuBar mb=new JMenuBar();
        mb.add(mfile);
        setJMenuBar(mb);
        
        ta=new JTextArea();
//        JScrollPane jsp=new JScrollPane(ta);
        JScrollPane jsp=new JScrollPane();
        jsp.setViewportView(ta);
//        add(ta);
        
        add(jsp);
        
        //새파일
        mNew.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                ta.setText("");
                setTitle("제목없음");
            }
        });
        
        //열기 (선택된 파일을 읽어들이기. fileread)
        mOpen.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc=new JFileChooser();
                if(fc.showOpenDialog(Memo.this)==JFileChooser.CANCEL_OPTION)
                    return//자신을 불러주는 부모창을 인수로함. Memo자기자신.
                f=fc.getSelectedFile(); //선택된 파일 
                setTitle(f.getName()); //선택된 파일의 이름 가져오기
                fileRead(f); //취소를 눌렀을경우 선택된 파일이 없기때문에 파일 읽어들이는 fileRead오류남
            }
        });
 
        //저장 (기존파일 없음=제목없음이면 새 창을 띄우기)
        mSave.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                if(getTitle().equals("제목없음")) { 
//                    JFileChooser fc=new JFileChooser();
//                    if(fc.showSaveDialog(Memo.this)==JFileChooser.CANCEL_OPTION)
//                        return;
//                    f=fc.getSelectedFile();
//                    fileSave(f);
//                    setTitle(f.getName());
                    mSaveAs.doClick(); //mSaveAs가 다시 실행되는 것과 같음.
                }else {    //기존파일 있음
                    fileSave(f);
                }
            }
        });
 
        //새이름 저장
        mSaveAs.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc=new JFileChooser();
                if(fc.showSaveDialog(Memo.this)==JFileChooser.CANCEL_OPTION)
                    return;
                f=fc.getSelectedFile();
//                System.out.println("파일 저장: "+f);
                fileSave(f);
                setTitle(f.getName());
            }
        });
        
        //끝내기
        mExit.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        
        
        setSize(500,400);
        setVisible(true);
        
    }
 
    public static void main(String[] args) {
        new Memo("제목없음");
    }
    
    //파일 읽기 메소드
    private void fileRead(File f) {
        try {
            FileReader fr=new FileReader(f);
            StringWriter sw=new StringWriter();
            while(true) {
                int ch=fr.read();
                if(ch==-1break;
                sw.write(ch);
            }
            ta.setText(sw.toString());
            sw.close();
            fr.close();
        } catch (FileNotFoundException n) {
            n.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
 
    //파일 저장 메소드
    private void fileSave(File f) {
        try {
            PrintStream ps=new PrintStream(f);
            ps.println(ta.getText());
            ps.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
    }
}
 
cs

 

 

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package swingTest;
 
import java.awt.GridLayout;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
 
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
 
public class Bank extends JFrame {
    HashMap<String, Integer> hm=new HashMap<String, Integer>(); //이름과 잔액을 기억하기 위함
    List lst;
    
    public Bank() {
        setTitle("BANK");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(1,2));
        
        JPanel left=new JPanel(); //왼쪽꺼
        left.setLayout(new GridLayout(5,1));
        
        JPanel p1=new JPanel(); //왼쪽 첫번째 줄
        p1.add(new JLabel("이름"));
        JTextField tfName=new JTextField(15);
        p1.add(tfName);
        
        JButton btn=new JButton("계좌생성"); //왼쪽 두번째 줄
        JPanel p2=new JPanel(); //왼쪽 세번째 줄
        p2.add(new JLabel("잔액")); 
        
        JTextField tfBalance=new JTextField(15);
        tfBalance.setEditable(false); //수정 못하게끔
        p2.add(tfBalance);
        
        JPanel p3=new JPanel(); //왼쪽 네번째 줄
        JTextField tfMoney=new JTextField(15);
        p3.add(tfMoney);    p3.add(new JLabel("원"));
        
        JPanel p4=new JPanel(); //왼쪽 다섯번째 줄
        JButton inputBtn=new JButton("예금");
        JButton outputBtn=new JButton("출금");
        JButton fileBtn=new JButton("파일로 저장");
        p4.add(inputBtn);    p4.add(outputBtn);    p4.add(fileBtn);
        
        left.add(p1);    left.add(btn);    left.add(p2); left.add(p3); left.add(p4);
        
        //오른쪽 화면
        lst=new List();
        //왼쪽 오른쪽 부착
        add(left);    add(lst);
        
        //계좌생성버튼 클릭
        btn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                //tfName의 내용을 가져와서 lst에 추가한다. 단 공백은 저장 안함
                if(tfName.getText().isEmpty()) return;
                lst.add(tfName.getText().trim()); //trim은 앞뒤 공백제거
                hm.put(tfName.getText(),0); //맵에 저장
                tfName.setText("");
            }
        });
        //리스트
        lst.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
            //리스트에서 선택한 이름을 tfName에 넣고 잔액은 tfBalance에 넣기
                String str=lst.getSelectedItem().trim(); //trim은 앞뒤 공백제거
                tfName.setText(str);
                tfBalance.setText(hm.get(str)+""); //키값인 str을 넣으면 밸류값(돈)이 반환. setText는 스트링. 
            }
        });
        
        //예금버튼 클릭
        inputBtn.addActionListener(new ActionListener() {
            /* 
             * 1. 리스트에서 선택한 계좌 잔액에
             * 2. tfMoney 만큼 더해서
             * 3. 잔액(tfBalance)을 고쳐주고 맵에 저장 
             */
            public void actionPerformed(ActionEvent e) {
             try {
                String key=lst.getSelectedItem().trim();
                int balance=hm.get(key); //기존잔액
                int value=balance+Integer.parseInt(tfMoney.getText()); //수정잔액
                tfBalance.setText(value+""); //화면에서 잔액수정
                hm.put(key, value); //맵 내용 수정
                tfMoney.setText(""); //편의를 위해 예금액 지우기
             }catch (NullPointerException x) {
                new MessageBox("오류""계좌를 선택해 주세요");
             }catch (NumberFormatException n) {
                new MessageBox("입력오류""숫자를 입력하세요");
             }
            }
        });
        
        //출금버튼 클릭
        outputBtn.addActionListener(new ActionListener() {
            /* 
             * 1. 리스트에서 선택한 계좌 잔액에
             * 2. tfMoney 만큼 빼서
             * 3. 잔액(tfBalance)을 고쳐주고 맵에 저장 
             */
            public void actionPerformed(ActionEvent e) {
             try {
                String key=lst.getSelectedItem().trim();
//                String key=tfName.getText();
                int balance=hm.get(key); //기존잔액    
                int value=balance-Integer.parseInt(tfMoney.getText()); //수정잔액
                if(value<0) {
                    new MessageBox("잔액부족!!", key+"님 잔액이 부족합니다."); //타이틀, 메시지
                    return;
                }
                tfBalance.setText(value+""); //화면에서 잔액수정
                hm.put(key, value); //맵 내용 수정
                tfMoney.setText(""); //편의를 위해 예금액 지우기
             }catch (NullPointerException x) {
                    new MessageBox("오류""계좌를 선택해 주세요");
             }catch (NumberFormatException n) {
                    new MessageBox("입력오류""숫자를 입력하세요");
            }
            }
        });
        
        //파일로 저장
        fileBtn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                //hm의 내용을 파일로 내보내겠다.(CapitalApp2의 quiz()메소드 참고)
                File dir=new File("src\\swingTest");
                File file=new File(dir,"myBank.txt");
                try {
                    FileWriter fw=new FileWriter(file);
                    Set<String>set=hm.keySet(); //key의 집합
                    Iterator<String>it=set.iterator();
                    while(it.hasNext()) {
                        String key=it.next(); //하나의 key구하기
                        fw.write(key+" "); //이름 내보내기
                        fw.write(hm.get(key)+"\n"); //잔액구하기
                    }
                    fw.close();
                }catch (IOException e1) {
                    new MessageBox("파일오류!!!""파일저장 실패");
                    e1.printStackTrace();
                }
            }
        });
        
        setSize(500,300);
        setVisible(true);
        load();
    }
    
    //파일에 저장한 내용을 list에 부르기
    private void load() {
        hm.clear();
        File dir=new File("src\\swingTest");
        File file=new File(dir,"myBank.txt");
        try {
            if(!file.exists()) {
                file.createNewFile();
            }
            Scanner sc=new Scanner(file); //파일로 읽어오기
            while(sc.hasNext()) {
                String name=sc.next().trim(); //이름
                int money=sc.nextInt(); //잔액
                hm.put(name, money); //맵에 저장
                lst.add(name+"\n"); //리스트에 이름 추가
            }
            sc.close();
        }catch(Exception e2) {
            e2.printStackTrace();
            System.out.println("오류");
        }
    }
    
    public static void main(String[] args) {
        new Bank();
        
    }
}
 
cs

 

 

  • 이름과 잔액을 쓰고 예금, 출금, 파일 저장 버튼 만들기 (Bank)

  • 계좌 잔액 부족시 경고 프레임 창 띄우기 (MessageBox)

 

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package swingTest;
 
import java.awt.GridLayout;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
 
public class Bank extends JFrame {
    HashMap<String, Integer> hm=new HashMap<String, Integer>(); //이름과 잔액을 기억하기 위함
    
    
    public Bank() {
        setTitle("BANK");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(1,2));
        
        JPanel left=new JPanel(); //왼쪽꺼
        left.setLayout(new GridLayout(5,1));
        JPanel p1=new JPanel(); //왼쪽 첫번째 줄
        p1.add(new JLabel("이름"));
        JTextField tfName=new JTextField(15);
        p1.add(tfName);
        
        JButton btn=new JButton("계좌생성"); //왼쪽 두번째 줄
        JPanel p2=new JPanel(); //왼쪽 세번째 줄
        p2.add(new JLabel("잔액")); 
        JTextField tfBalance=new JTextField(15);
        tfBalance.setEditable(false); //수정 못하게끔
        p2.add(tfBalance);
        
        JPanel p3=new JPanel(); //왼쪽 네번째 줄
        JTextField tfMoney=new JTextField(15);
        p3.add(tfMoney);    p3.add(new JLabel("원"));
        
        JPanel p4=new JPanel(); //왼쪽 다섯번째 줄
        JButton inputBtn=new JButton("예금");
        JButton outputBtn=new JButton("출금");
        JButton fileBtn=new JButton("파일로 저장");
        p4.add(inputBtn);    p4.add(outputBtn);    p4.add(fileBtn);
        
        left.add(p1);    left.add(btn);    left.add(p2); left.add(p3); left.add(p4);
        
        //오른쪽 화면
        List lst=new List();
        //왼쪽 오른쪽 부착
        add(left);    add(lst);
        
        //계좌생성버튼 클릭
        btn.addActionListener(new ActionListener() {
            
            public void actionPerformed(ActionEvent e) {
                //tfName의 내용을 가져와서 lst에 추가한다. 단 공백은 저장 안함
                if(tfName.getText().isEmpty()) return;
                lst.add(tfName.getText().trim()); //trim은 공백제거
                hm.put(tfName.getText(),0); //맵에 저장
                tfName.setText("");
            }
        });
        //리스트
        lst.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
            //리스트에서 선택한 이름을 tfName에 넣고 잔액은 tfBalance에 넣기
                String str=lst.getSelectedItem();
                tfName.setText(str);
                tfBalance.setText(hm.get(str)+""); //키값인 str을 넣으면 밸류값(돈)이 반환. setText는 스트링. 
            }
        });
        
        //예금버튼 클릭
        inputBtn.addActionListener(new ActionListener() {
            /* 
             * 1. 리스트에서 선택한 계좌 잔액에
             * 2. tfMoney 만큼 더해서
             * 3. 잔액(tfBalance)을 고쳐주고 맵에 저장 
             */
            public void actionPerformed(ActionEvent e) {
                String key=lst.getSelectedItem();
                int balance=hm.get(key); //기존잔액
                int value=balance+Integer.parseInt(tfMoney.getText()); //수정잔액
                tfBalance.setText(value+""); //화면에서 잔액수정
                hm.put(key, value); //맵 내용 수정
                tfMoney.setText(""); //편의를 위해 예금액 지우기
            }
        });
        
        //출금버튼 클릭
        outputBtn.addActionListener(new ActionListener() {
            /* 
             * 1. 리스트에서 선택한 계좌 잔액에
             * 2. tfMoney 만큼 빼서
             * 3. 잔액(tfBalance)을 고쳐주고 맵에 저장 
             */
            public void actionPerformed(ActionEvent e) {
                String key=lst.getSelectedItem();
                int balance=hm.get(key); //기존잔액    
                int value=balance-Integer.parseInt(tfMoney.getText()); //수정잔액
                if(value<0) {
                    new MessageBox("잔액부족!!", key+"님 잔액이 부족합니다."); //타이틀, 메시지
                    return;
                }
                tfBalance.setText(value+""); //화면에서 잔액수정
                hm.put(key, value); //맵 내용 수정
                tfMoney.setText(""); //편의를 위해 예금액 지우기
            }
        });
        
        setSize(500,300);
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new Bank();
        
    }
}
 
cs

 


 

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
package swingTest;
 
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;
 
public class MessageBox extends JFrame{
    public MessageBox(String title, String msg) {
    setTitle(title);
    setLayout(new FlowLayout());
//    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Bank클래스의 프레임까지 같이 닫아버림
    JButton closeBtn=new JButton("닫기");
    JLabel lbl=new JLabel(msg);
    add(lbl);
    add(closeBtn);
    closeBtn.addActionListener(new ActionListener() {
        
        public void actionPerformed(ActionEvent e) {
            dispose(); //자신의 창만 닫도록 함
        }
    });
    setSize(300,100);
    setVisible(true);
    }
    
    
}
 
cs
  • CalTest 클래스를 복사하여 내부 클래스로 나타내기 (CalTest2) (Anonymous Inner Type 연습. 중복된 코드는 많으나 객체와 이벤트를 붙임으로써 명료해진다.)

 

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
package swingTest;
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 CalTest2 extends JFrame {
     private JTextField tf1, tf2, tf3;
     
     public CalTest2() {
          setTitle("계산기2");
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setLayout(new FlowLayout());
          tf1=new JTextField(5); //숫자 1
          tf2=new JTextField(5); //숫자 2
          tf3=new JTextField(20); //결과
          
          JButton b1=new JButton("+");
          JButton b2=new JButton("-");
          JButton b3=new JButton("*");
          JButton b4=new JButton("/");
          
          b1.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   int a= Integer.parseInt(tf1.getText());
                   int b= Integer.parseInt(tf2.getText());
                   tf3.setText(a+b+"");
              }
          });
          b2.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   int a= Integer.parseInt(tf1.getText());
                   int b= Integer.parseInt(tf2.getText());
                   tf3.setText(a-b+"");
              }
          });
          b3.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   int a= Integer.parseInt(tf1.getText());
                   int b= Integer.parseInt(tf2.getText());
                   tf3.setText(a*b+"");
              }
          });
          b4.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   int a= Integer.parseInt(tf1.getText());
                   int b= Integer.parseInt(tf2.getText());
                   tf3.setText(a/b+"");
              }
          });
          
          add(new JLabel("숫자1"));
          add(tf1);
          add(new JLabel("숫자2"));
          add(tf2);
          add(b1); add(b2); add(b3); add(b4);
          add(new JLabel("결과"));
          add(tf3);
          
          setSize(700,100);
          setVisible(true);
     }
     
     public static void main(String[] args) {
          new CalTest2();
     }
}
cs

 

 

 

 

  • addActionListener 메소드의 매개변수에 액션 리스너 생성, addItemLister 메소드의 매개변수에 ItemStateChanged 생성 (ListTest3)

 

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
88
89
90
91
92
93
94
95
96
97
package swingTest;
 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.List; //util에 있는 List는 Arraylist
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
 
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
public class ListTest3 extends JFrame{
    private JTextField tf;
    private JTextArea ta;
    private List list;
    private JCheckBox cb;
    
    public ListTest3() { //생성자 만들기
        setTitle("List 예제3");
        setLayout(new BorderLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JPanel p1=new JPanel();
        tf=new JTextField(15);
        JButton btn=new JButton("추가");
        cb=new JCheckBox("다중선택");
        p1.setBackground(Color.DARK_GRAY);
        p1.add(tf); p1.add(btn); p1.add(cb);
        
        JPanel p2=new JPanel(new GridLayout(1,2));
        list=new List();
        ta=new JTextArea();
        p2.add(list); p2.add(ta);
 
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(tf.getText().isEmpty()) return;
                list.add(tf.getText());
                tf.setText(""); //비우기
            }
        });
        
        tf.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(tf.getText().isEmpty()) return;
                list.add(tf.getText());
                tf.setText(""); //비우기
            }
        });
        
        list.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                ta.setText("");
                if(list.isMultipleMode()) { //리스트가 다중선택
                    String []arr=list.getSelectedItems();
                    for(int i=0;i<arr.length;i++) {
                        ta.append(arr[i]+"\n");
                    }
                }else { //리스트가 단일선택
                    //리스트(list)에서 선택한 내용을 textarea(ta)에 출력하기
                    ta.setText(list.getSelectedItem());
                }
        }
        });
        
        cb.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if(cb.isSelected()) { //checkbox 선택인지->리스트가 다중모드
                    list.setMultipleMode(true);
                }else { //checkbox 해제인지->리스트가 단일모드
                    list.setMultipleMode(false);
                }
            }
        });
        
        add(BorderLayout.NORTH,p1);
        add(BorderLayout.CENTER,p2);
        
        setSize(400,400);
        setVisible(true);
        
        
    }
    
    public static void main(String[] args) {
        new ListTest3(); //생성자 부르기
    }
 
    
}
cs

 

+ Recent posts