이론




자바FX

***혹시 RUN하는데 targetException이 뜬다면,  각 모듈의 id와 UI멤버 변수들이 일치하는지 확인할 것 ***


단위작업 : 하나의 통합된 작업을 세부단위로 분해하여, 가장 작은 단위의 직업을 말한다.


javafx에서의 스레드 핸들링

1.Platform.runLater()( == handler.post)

2.Task(바인딩 개념 : Runnable 인터페이스를 상속)

call() -> 스레드를 핸들링한다(진짜 스레드가 해야하는 일)

successed() -> UI처리 -> Update()/UI값 바인딩

cancle() 

service()

3.Service


안드로이드에서 Thread가 safe한가?

safe하지 않다. 안드로이드 자체에서는, UI Thread를 기본 스레드로 핸들링 했을 때 과부하가 걸릴 수 있기 때문.

Thread UI Handler와 Thread 안에서 handler.post를 이용해 handler와 통신하는 방법이 있고, 두번째로 AsynchTask가 있다.


모델 == 안드로이드의 베이스어댑터



실습


stackpandemo0525.FXMLDocumentController.java

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 stackpandemo0525;
 
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
 
 
public class FXMLDocumentController implements Initializable {
     
    @FXML
    private Label label;
    //UI멤버
    @FXML
    private Button nextBtn,prevBtn;
    @FXML
    private StackPane rootP;
     
    private ObservableList<Node> childs;
    private Node firstNode, secondNode, tableNode;
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        childs = this.rootP.getChildren();
        firstNode = childs.get(childs.size()-1);
        secondNode = childs.get(childs.size()-2);
    }   
     
    @FXML
    private void nextButtonAction(ActionEvent event) {
        firstNode.setVisible(false);
        firstNode.toBack();
        secondNode.setVisible(true);
    }
    @FXML
    private void prevButtonAction(ActionEvent event) {
        secondNode.setVisible(false);
        secondNode.toBack();
        firstNode.setVisible(true);
    }
     
     
}


stackpaneex.FXMLDocumentController.java

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
package stackpaneex;
 
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
 
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.StackPane;
 
 
public class FXMLDocumentController implements Initializable {
     
    @FXML
    private Button listBtn;
     
    @FXML
    private Button tableBtn;
     
    @FXML
    private Button tablePreBtn;
     
    @FXML
    private Button listPreBtn;
     
    @FXML
    private StackPane rootP;
     
    @FXML
    private ListView listview;
     
    @FXML
    private TableView tableview;
     
    Node firstNode;
    Node secondNode;
    Node threeNode;
     
     
     
    @FXML
    private void handleButtonAction(ActionEvent event) {
        System.out.println("You clicked me!");
    }
     
    @FXML
    private void listViewButtonAction(ActionEvent event) {
        System.out.println("listViewButtonAction clicked!");
        firstNode.setVisible(false);
        firstNode.toBack();
        threeNode.toBack();
        //다음 node를 활성화 시킨다.
        secondNode.setVisible(true);
         
        List<String> listData = new ArrayList<>();
        for(int i = 0; i < 20; i++){
            listData.add("My data : XData"+i);
        }
         
        listview.setItems(FXCollections.observableArrayList(listData));
    }
     
    @FXML
    private void tableViewButtonAction(ActionEvent event) {
        System.out.println("tableViewButtonAction clicked!");
        firstNode.setVisible(false);
        firstNode.toBack();
        secondNode.toBack();
        threeNode.setVisible(true);
        List<Phone> pList = new ArrayList<>();
        for(int i = 0; i < 20; i++){
            pList.add(new Phone(("갤럭시노트"+i), "phone"+i+".png"));
        }
        ObservableList phoneList = FXCollections.observableArrayList(pList);
        TableColumn smartPhone = (TableColumn) tableview.getColumns().get(0);
        smartPhone.setCellValueFactory(new PropertyValueFactory("smartPhone"));
        TableColumn smartImage = (TableColumn) tableview.getColumns().get(1);
        smartImage.setCellValueFactory(new PropertyValueFactory("Image"));
        tableview.setItems(phoneList);
    }
     
    @FXML
    private void tablePreButtonAction(ActionEvent event) {
        System.out.println("tablePreButtonAction clicked!");
        threeNode.setVisible(false);
        threeNode.toBack();
        firstNode.toFront();
        firstNode.setVisible(true);
    }
     
    @FXML
    private void listPreButtonAction(ActionEvent event) {
        System.out.println("listPreButtonAction clicked!");
        secondNode.setVisible(false);
        secondNode.toBack();
        firstNode.toFront();
        firstNode.setVisible(true);
    }
     
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        //StackPane의 자식노드를 모두 가져온다.
        ObservableList<Node> childs = this.rootP.getChildren();
        //첫번째 node : 제일 처음 보이는 pane(next)
        System.out.println("test childs size ======= : " + childs.size());
        firstNode = childs.get(childs.size()-1);
        //두번째 node : 숨겨진 pane(prev)
        secondNode = childs.get(childs.size()-2);
        threeNode = childs.get(childs.size()-3);
    }   
     
}


stackpaneex.Phone.java

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
package stackpaneex;
 
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
 
 
public class Phone {
     
    //SimpleXXPreperty : FX자료형
    private SimpleStringProperty smartPhone;
    private SimpleStringProperty image;
    private SimpleIntegerProperty price;
     
    public Phone(String smartPhone, String image){
        this.smartPhone = new SimpleStringProperty(smartPhone);
        this.image = new SimpleStringProperty(image);
        this.price = new SimpleIntegerProperty(100000);
    }
    public String getSmartPhone(){
        return smartPhone.get();
    }
     
    public void setSmartPhone(String smartPhone){
        this.smartPhone.set(smartPhone);
    }
     
    public String getImage(){
        return image.get();
    }
     
    public void setImage(String image){
        this.image.set(image);
    }
     
    public int getPrice(){
        return price.get();
    }
     
    public void setPrice(int price){
        this.price.set(price);
    }
     
}


threaduidemo0525.FXMLDocumentController.java

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
package threaduidemo0525;
 
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
 
public class FXMLDocumentController implements Initializable {
     
    @FXML
    private Label label;
     
    boolean flag;
     
    private CustomService service;
     
    @FXML
    private void handleButtonAction(ActionEvent event) {
        System.out.println("You clicked me!");
        label.setText("Hello World!");
    }
     
    @FXML
    private void startButtonAction(ActionEvent event){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
        flag = false;
        Thread th = new Thread(new Runnable() {
            @Override
            public void run() {
                while(!flag){
                    String times = sdf.format(new Date());
                    System.out.println(times);
                    //Exception in thread "Thread-4" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            label.setText(times);
                        }
                    });
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
        th.setDaemon(true);
        th.start();
    }
     
    @FXML
    private void stopButtonAction(ActionEvent event){
        flag = true;
        System.out.println("stopButtonAction clicked");
    }
     
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        service = new CustomService();
    }   
     
    @FXML
    private void startButtonAction2(ActionEvent event){
        service.start();
    }
     
    @FXML
    private void stopButtonAction2(ActionEvent event){
        flag = true;
        service.cancel();
    }
     
    class CustomService extends Service<String>{
        @Override
        protected Task<String> createTask(){
            System.out.println("Clicked Task");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            flag = false;
            // step 2) task
            Task<String> task = new Task<String>(){
                @Override
                protected String call() throws Exception {
                    System.out.println("Clicked call");
                    String times = null;
                    while(!flag){
                        System.out.println("Clicked flag" + flag);
                        times = sdf.format(new Date());
                        //updateMessage(times) : call()가 호출되는 값을 bind를 통해서
                        //succeeded() 전달한다.
                        updateMessage(times);
                        try{
                            Thread.sleep(200);
                        }catch (InterruptedException ex){
                            if(isCancelled()){
                                break;
                            }
                            ex.printStackTrace();
                        }                        
                    }
                    return times;
                }
            };
            //라벨에 값을 전달하기 위해서 bind 한다.
            label.textProperty().bind(task.messageProperty());
            return task;
        }
        //성공적으로 call()의 값이 전달 되었을 때
        //cancelled() -> cancle()호출 시 , failed() : 예외발생시
         
        @Override
        public void succeeded(){
            System.out.println("value : " + getValue());
            label.setText("value : " + getValue());
        }
    }
}


threaduidemo0525.threaduidemo0525.java

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
package threaduidemo0525;
 
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
 
public class ThreadUIDemo0525 extends Application {
     
    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("TreadFXML.fxml"));
         
        Scene scene = new Scene(root);
        //StyleSheet 추가
        scene.getStylesheets().add(getClass().getResource("app.css").toString());
        stage.setTitle("ThreadDemo");
        stage.setScene(scene);
        stage.show();
    }
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
     
}


threaduidemo0525.app.css

1
2
3
4
5
6
7
8
9
Label{
    -fx-padding: 5;
    -fx-color:red;
}
.button:hover{
    -fx-border-width: 1;
    -fx-border-radius: 20;
    -fx-background-color: linear-gradient(#2A5058,#61a2b1)
}


'학원수업 > 자바' 카테고리의 다른 글

학원 46일차 복습(5/23)  (0) 2018.05.23
학원 13일차 복습(3/30)  (0) 2018.03.30
학원 12일차 복습(3/29)  (0) 2018.03.30
학원 11일차 복습(3/28)  (0) 2018.03.28
학원 10일차 복습(3/27)  (0) 2018.03.27

이론



http://gluonhq.com/products/mobile/javafxports/get/ 맨 밑에꺼 다운로드

unzip armv6hf-sdk-8.60.9.zip

http://docs.gluonhq.com/javafxports/#anchor-1 참고

> cd armv6hf-sdk/

> cd rt

> cd lib/

> sudo cp ext/jfxrt.jar /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/ext/

> sudo cp arm/* /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/arm/

> sudo cp javafx.platform.properties /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/

> sudo cp javafx.properties /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/

> sudo cp jfxswt.jar /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/


-라즈베리의 dio.jar 파일을 netbeans의 libraries에 넣어준다

자바FX 프로젝트 빌드후 dist안의 파일 복사후 라즈베리에서

> sudo java -jar testpi.jar 



java ME doc

https://wiki.openjdk.java.net/display/dio/Main  

-mercurial (Git같은 것,  소프트웨어 개발을 위한 크로스-플랫폼 분산 버전 관리 도구)

> sudo apt-get install mercurial

> hg clone http://hg.openjdk.java.net/dio/dev

> ls (dev 확인)

> cd dev

> export PI_TOOLS=/usr

> export JAVA_HOME=

> export JAVA_HOME=/usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/

> make

> ls -l (build 확인)

> cd deviceio/lib/

>  sudo cp arm/libdio.so /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/arm/

>  sudo cp ext/dio.jar /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/ext/




 sudo nano /usr/lib/jvm/jdk-8-oracle-arm32-vfp-hflt/jre/lib/security/java.policy

permission jdk.dio.DeviceMgmtPermission "*:*", "open";

permission jdk.dio.gpio.GPIOPinPermission "*:*", "open,setdirection";

permission jdk.dio.gpio.GPIOPortPermission "*:*";

permission jdk.dio.i2cbus.I2CPermission "*:*";

permission jdk.dio.spi.SPIPermission "*:*";

permission jdk.dio.spibus.SPIPermission "*:*";

permission jdk.dio.uart.UARTPermission "*:*", "open";

추가하기


fritzing : 회로도 그리는 툴

http://fritzing.org/download/?donation=0 에서 windows 64bit 다운로드



실습


FXMLDocumentController.java

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
package testpi;
 
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ToggleButton;
 
public class FXMLDocumentController implements Initializable {
 
    @FXML
    private Label label;
    @FXML
    private Button btnExit;
    @FXML
    private ToggleButton btnLED;
 
    private static Led led;
 
    @FXML
    private void handleButtonAction(ActionEvent event) {
        Platform.exit();
    }
 
    @FXML
    private void onActionBtnLED(ActionEvent event) {
        try {
            if (btnLED.isSelected()) {
                label.setText("LED On!");
                led.on();
            } else {
                label.setText("LED Off!");
                led.off();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
 
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        if (led == null) {
            try {
                led = new Led(27);
                btnLED.setSelected(led.isOn());
            } catch (IOException ex) {
                System.out.println("핀을 찾을 수 없음");
                ex.printStackTrace();
            }
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    try {
                        led.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }
    }
 
}


LED.java

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
package testpi;
 
import java.io.IOException;
 
import jdk.dio.ClosedDeviceException;
 
import jdk.dio.DeviceManager;
 
import jdk.dio.UnavailableDeviceException;
 
import jdk.dio.gpio.GPIOPin;
 
import jdk.dio.gpio.GPIOPinConfig;
 
public class Led {
    private GPIOPin gpioPin;
    public Led(int inNum) throws IOException {
        gpioPin = DeviceManager.open(new GPIOPinConfig.Builder()
                .setPinNumber(inNum)
                .setDirection(GPIOPinConfig.DIR_OUTPUT_ONLY)
                .build()
        );
    }
    public void on() throws UnavailableDeviceException, ClosedDeviceException, IOException {
        gpioPin.setValue(true);
    }
    public boolean isOn() throws UnavailableDeviceException, ClosedDeviceException, IOException {
        return gpioPin.getValue();
    }
    public void off() throws UnavailableDeviceException, ClosedDeviceException, IOException {
        gpioPin.setValue(false);
    }
    public void close() throws IOException {
        gpioPin.close();
    }
}


'학원수업 > 자바' 카테고리의 다른 글

학원 47일차 복습(5/25)  (0) 2018.05.28
학원 13일차 복습(3/30)  (0) 2018.03.30
학원 12일차 복습(3/29)  (0) 2018.03.30
학원 11일차 복습(3/28)  (0) 2018.03.28
학원 10일차 복습(3/27)  (0) 2018.03.27

평가



60문제 풀이 : 만점

Adapter디자인, URL커낵터 체크하기


  



'학원수업 > 자바' 카테고리의 다른 글

학원 47일차 복습(5/25)  (0) 2018.05.28
학원 46일차 복습(5/23)  (0) 2018.05.23
학원 12일차 복습(3/29)  (0) 2018.03.30
학원 11일차 복습(3/28)  (0) 2018.03.28
학원 10일차 복습(3/27)  (0) 2018.03.27

이론



서버 코드: 클라이언트로부터 소켓의 연결 요청이 오면 accept()메서드가 호출이 되어서 Socket객체를 반환하고

다중 소켓을 처리하기 위해서 ArrayList에 적재한다.

이때 ArrayList에 들어갈 소켓들은 스레드가 담당하게 되며, 접속한 클라이언트당 소켓이 각각 ArrayList에 들어가게 되는 구조이다.

Thread는 결국 각 소켓의 연결된 스트림을 담당하게 되고 서버는 이 스트림을 통해서 각각의 클라이언트에게 응답메세지를 전달하게 된다.



1. 서버 시작을 위해서 port를 9999번으로 입력한 서버객체를 생성한다.

2. 생성자 초기화

3. 생성된 Ex1_Server객체의 execute메서드를 호출한다.

4.무한반복하면서 Socket의 accept() 접속을 대기한다.

5. XXIP의 port서버로 접속을 한다

6.접속해온 클라이언트의 소켓을 ServerThread가 관리하도록 한명이 접속해 올때 마다 생성시켜두고

                이것을 Generic로 가지고 있는 ArrayList에 그 주소를 넣어서 소켓의 주소를 메모리영역에 참조하게 한다.

                 스레드는 start한다

7번 접속후 사용자가 소켓을 통해서 메세지를 전달한다.

        서버의 ServerThread가 관리하는 Socket과 통신한다.

        Output으로 보내면 / 서버에서는 InputStream으로 받는다.

         talk/ 임의로 약속된 서버와 클라이언트의 프로토콜이 된다

8. 지속적인 메세지를 받아내는 블록킹 메서드

9. 결국 클라이언트의 프로토콜을 분석해서 접속한 모든 클라이언트에 전송한다.(브로드캐스팅)

 10.서버로부터 sendMsg가 호출이 되어서 전송되어온  메세지를 받아서 프로토콜을 분석하여 클라이언트가 해야할

            일을 정의한 스레드 익명 내부클래스임

  


실습


ex1.CanvasDemo

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
package ex1;
 
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
 
public class CanvasDemo extends javax.swing.JFrame {
 
    private int x, y, d;
 
    /**
     * Creates new form CanvasDemo
     */
    public CanvasDemo() {
        x = 100;
        y = 100;
        d = 20;
        initComponents();
        canvas1.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                x = e.getX();
                y = e.getY();
                canvas1.repaint();
            }
 
        });
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        jPanel1 = new javax.swing.JPanel();
        canvas1 = new java.awt.Canvas(){
            @Override
            public void paint(Graphics g) {
                g.setColor(Color.red);
                g.fillOval(x, y, d, d);
            }
            @Override
            public void update(Graphics g) {
                paint(g);
            }
        }
        ;
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jPanel1.setBackground(new java.awt.Color(255, 153, 153));
 
        canvas1.setBackground(new java.awt.Color(255, 255, 255));
 
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(338, Short.MAX_VALUE)
                .addComponent(canvas1, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addComponent(canvas1, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(39, Short.MAX_VALUE))
        );
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                       
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CanvasDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CanvasDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CanvasDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CanvasDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CanvasDemo().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private java.awt.Canvas canvas1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                  
}

ex1.CanvasTemplate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package ex1;
 
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
 
public class CanvasTemplate extends JFrame{
    private int x,y,d;
 
    public CanvasTemplate() {
        Canvas can = new Canvas(){
            @Override
            public void update(Graphics g) {
                paint(g);
            }
            @Override
            public void paint(Graphics g) {
                g.setColor(Color.red);
                g.fillOval(x, y, d, d);
            }
        };
    }
}

ex1.ServerThread

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
package ex1;
 
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class ServerThread extends Thread {
 
    private Socket socket;//서버로부터 위임받을 소켓의 주소
    private Ex1_Server server;//서버의 주소
    private BufferedReader in;//소켓으로부터 연결될 두 스트림
    private PrintWriter pw;
    private String reip;
 
    //서버가 현재 객체를 생성시 소켓의 주소와 서버의 주소를 주입해서 전달
    public ServerThread(Socket socket, Ex1_Server server) {
        this.socket = socket;
        this.server = server;
        reip = socket.getInetAddress().getHostAddress();
        System.out.println("접속한 사용자의 IP: " + reip);
 
        try {
            pw = new PrintWriter(new BufferedOutputStream(socket.getOutputStream()), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
 
    }
 
    //스레드에게 시킬 일을 정의
    @Override
    public void run() {
        //소켓으로 부터 클라이언트의 메세지를 받아내는 일을 위임받았음
        while (true) {
            try {
                //8. 지속적인 메세지를 받아내는 블록킹 메서드
                String msg = in.readLine();
                // talk/nickname/msg/null/null
                // draw/x-y/color/null/null/null
                System.out.println("Server Log: [Client Message]"+msg);
                transMsg(msg);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
 
    //메시지를 분석하는 메서드
    private void transMsg(String msg) {
        //ex) talk/user/msg/null
        // draw/color/x/y/null
        // /구분으로 만든 서버와 클라이언트간의 통신 규약-protocol
        // Exx1_StringTokenizer를 만들어서 연습
        StringTokenizer stn = new StringTokenizer(msg, "/");
        //리펙토링구간
        String str1 = stn.nextToken();
        String str2 = stn.nextToken();
        String str3 = stn.nextToken();
        String str4 = stn.nextToken();
        String str5 = stn.nextToken();
        server.sendMsg(str1,str2,str3,str4,str5,reip);
    }
 
    public PrintWriter getPw() {
        return pw;
    }
     
 
}

ex1.Server

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
package ex1;
 
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
 
//서버 코드: 클라이언트로부터 소켓의 연결 요청이 오면 accept()메서드가 호출이 되어서 Socket객체를 반환하고
//다중 소켓을 처리하기 위해서 ArrayList에 적재한다.
//이때 ArrayList에 들어갈 소켓들은 스레드가 담당하게 되며, 접속한 클라이언트당 소켓이 각각 ArrayList에 들어가게 되는 구조이다.
//Thread는 결국 각 소켓의 연결된 스트림을 담당하게 되고 서버는 이 스트림을 통해서 각각의 클라이언트에게 응답메세지를 전달하게 된다.
 
public class Ex1_Server {
    private ServerSocket ss;
    private ArrayList<ServerThread> clist;
    private String reip;
 
    public Ex1_Server(int port) {
            //2. 생성자 초기화
            //소켓생성, ServerThread를 저장할 ArrayList생성
        try {
            ss= new ServerSocket(port);
            clist = new ArrayList<>();
            System.out.println("Start Server!");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    public void execute(){
        //4.무한반복하면서 Socket의 accept() 접속을 대기한다.
        while(true){
            try {
                Socket s = ss.accept();
                //----------------------
                //6.접속해온 클라이언트의 소켓을 ServerThread가 관리하도록 한명이 접속해 올때 마다 생성시켜두고
                //이것을 Generic로 가지고 있는 ArrayList에 그 주소를 넣어서 소켓의 주소를 메모리영역에 참조하게 한다.
                // 스레드는 start한다.
                ServerThread ct = new ServerThread(s,this);
                clist.add(ct); //ArrayList에 클라이언트를 담당할 스레드를 저장한다.
                ct.start(); // 스레드를 시작한다.
                System.out.println("Current number of Clients :"+clist.size());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
             
        }
    }
 
    public void sendMsg(String str1, String str2, String str3, String str4, String str5, String reip) {
        // str1/str2/str3/str4/str5
        //서버를 제작할? 각 조에 맞는 프로토콜을 설계하기 바람
        String str = "";
        if(str1.equals("talk")){
            str = "talk/["+reip+"]"+str2+"/"+str3+"/"+str4+"/"+str5;
        }else if(str1.equals("draw")){
            //이런식으로... x/y/color등을 보낼 수 있다.
            str= "draw/"+str2+"/"+str3+"/"+str4+"/"+str5;
        }
        //모든 유저에게 브로드캐스팅을 한다.
        //모든 유저는 for문을 사용해서
        for(ServerThread c : clist){
            c.getPw().println(str);
        }
    }
    public static void main(String[] args) {
        //1. 서버 시작을 위해서 port를 9999번으로 입력한 서버객체를 생성한다.
        Ex1_Server es = new Ex1_Server(9999);
        //3. 생성된 Ex1_Server객체의 execute메서드를 호출한다.
        es.execute();
    }
}

ex1.Chat

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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
package ex1;
 
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.StringTokenizer;
 
public class Ex1_Chat extends javax.swing.JFrame {
 
    private int x, y; //캔버스에 그림의 좌표
    private int d;  //나의 붓크기의 값
    private Color col; //나의 색상, 전달색상
    private CardLayout card; //카드레이아웃*****
    private Socket s; //소켓의 주소
    private PrintWriter pw;//서버로 전송할 스트림!
 
    public Ex1_Chat() {
        x = 0;
        y = 0;
        d = 20;
        col = Color.RED;  //초기값 설정
        initComponents();
        card = (CardLayout) pp.getLayout();
        canvas1.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                x = e.getX();
                y = e.getY();
                 String msg = "draw/"+x+"/"+y+"/"+col.getRGB()+"/"+d; // draw형식에 맞춰서 나열해준다.
                pw.println(msg); // 소켓을 통해서 연결된 스트림으로 서버로 메세지를 송출!
                canvas1.repaint();
            }
        });
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        pp = new javax.swing.JPanel();
        p1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        hostv = new javax.swing.JTextField();
        portv = new javax.swing.JTextField();
        nickNamev = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        p2 = new javax.swing.JPanel();
        canvas1 = new java.awt.Canvas(){
            @Override
            public void paint(Graphics g) {
                g.setColor(col);
                g.fillOval(x, y, d, d);
            }
            @Override
            public void update(Graphics g) {
                paint(g);
            }
        };
        jScrollPane1 = new javax.swing.JScrollPane();
        msgView = new javax.swing.JTextArea();
        chat = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        nick = new javax.swing.JLabel();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        pp.setBackground(new java.awt.Color(255, 255, 204));
        pp.setLayout(new java.awt.CardLayout());
 
        p1.setBackground(new java.awt.Color(255, 153, 153));
 
        jLabel1.setText("IP:");
 
        jLabel2.setText("NickName:");
 
        jLabel3.setText("port:");
 
        hostv.setText("192.168.0.118");
 
        portv.setText("9999");
 
        nickNamev.setText("김길동님");
 
        jButton1.setText("접속");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
 
        javax.swing.GroupLayout p1Layout = new javax.swing.GroupLayout(p1);
        p1.setLayout(p1Layout);
        p1Layout.setHorizontalGroup(
            p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(p1Layout.createSequentialGroup()
                .addGroup(p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(p1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, p1Layout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addGroup(p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(p1Layout.createSequentialGroup()
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(portv, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(p1Layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(hostv, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(p1Layout.createSequentialGroup()
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(nickNamev, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(470, Short.MAX_VALUE))
        );
        p1Layout.setVerticalGroup(
            p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(p1Layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addGroup(p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(hostv, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(portv, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nickNamev, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(40, 40, 40)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(345, Short.MAX_VALUE))
        );
 
        pp.add(p1, "c1");
 
        p2.setBackground(new java.awt.Color(51, 153, 255));
 
        canvas1.setBackground(new java.awt.Color(255, 255, 255));
 
        jScrollPane1.setPreferredSize(new java.awt.Dimension(167, 300));
 
        msgView.setColumns(20);
        msgView.setRows(5);
        jScrollPane1.setViewportView(msgView);
 
        chat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chatActionPerformed(evt);
            }
        });
 
        jLabel4.setText("붓크기");
 
        jButton2.setText("X");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
 
        jButton3.setText("Red");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
 
        jButton4.setText("Pink");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
 
        jButton5.setText("Black");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
 
        jButton6.setText("지우개");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
 
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
 
        nick.setText("김길동님");
 
        javax.swing.GroupLayout p2Layout = new javax.swing.GroupLayout(p2);
        p2.setLayout(p2Layout);
        p2Layout.setHorizontalGroup(
            p2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(p2Layout.createSequentialGroup()
                .addGroup(p2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(p2Layout.createSequentialGroup()
                        .addGap(48, 48, 48)
                        .addComponent(nick, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(chat, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, p2Layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE)
                .addGroup(p2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, p2Layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addGap(26, 26, 26)
                        .addComponent(jButton4)
                        .addGap(32, 32, 32)
                        .addComponent(jButton5)
                        .addGap(28, 28, 28)
                        .addComponent(jButton6)
                        .addGap(84, 84, 84))
                    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(canvas1, javax.swing.GroupLayout.PREFERRED_SIZE, 407, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(42, 42, 42))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, p2Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(90, 90, 90))
        );
        p2Layout.setVerticalGroup(
            p2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(p2Layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(p2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(canvas1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                .addGroup(p2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton4)
                    .addComponent(jButton5)
                    .addComponent(jButton6)
                    .addComponent(chat, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nick, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(p2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(47, 47, 47))
        );
 
        pp.add(p2, "c2");
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                       
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        try {
            //5. XXIP의 port서버로 접속을 한다
            s = new Socket(hostv.getText().trim(), Integer.parseInt(portv.getText()));
            //-------------------------------------------
            pw = new PrintWriter(new BufferedOutputStream(s.getOutputStream()), true);
            card.show(pp, "c2");
            // 10.서버로부터 sendMsg가 호출이 되어서 전송되어온  메세지를 받아서 프로토콜을 분석하여 클라이언트가 해야할
            //일을 정의한 스레드 익명 내부클래스임
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        new Thread(new Runnable() {
            private BufferedReader br = null;
 
            @Override
            public void run() {
                try {
                    br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                    while (true) {
                        String str = br.readLine();
                        StringTokenizer stz = new StringTokenizer(str, "/");
                        //프로토콜을 분석해야 하는 구문
                        // talk/[null]xxx님/message
                        String protocol = stz.nextToken();
                        if (protocol.equals("talk")) {
                            String msg = "[" + stz.nextToken() + "]:" + stz.nextToken();
                            msgView.append(msg + "\n");
                            //채팅의 위치를 잡아주는 기능
                            msgView.setCaretPosition(msgView.getText().length());
                        } else if (protocol.equals("draw")){
                             x= Integer.parseInt(stz.nextToken());
                             y= Integer.parseInt(stz.nextToken());
                             col = new Color(Integer.parseInt(stz.nextToken()));
                             d = Integer.parseInt(stz.nextToken());
                            canvas1.repaint();
                            System.out.println("/"+x+"/"+y+"/"+col+"/"+d);
                        }
                    }
                } catch (IOException ex) {
                }
            }
        }).start();
 
 
    }                                       
 
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       
 
    private void chatActionPerformed(java.awt.event.ActionEvent evt) {                                    
 
        // 7번 접속후 사용자가 소켓을 통해서 메세지를 전달한다.
        // 서버의 ServerThread가 관리하는 Socket과 통신한다.
        // Output으로 보내면 / 서버에서는 InputStream으로 받는다.
        // talk/ 임의로 약속된 서버와 클라이언트의 프로토콜이 된다.
        String msg = "talk/" + nickNamev.getText() + "/" + chat.getText() + "/null/null";
        pw.println(msg); // 소켓을 통해서 연결된 스트림으로 서버로 메세지를 송출!
        chat.setText("");
        chat.requestFocus(); // 커서를 처음으로 잡아줌
    }                                   
 
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        col = Color.RED;
    }                                       
 
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        col = Color.PINK;
    }                                       
 
    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        col = Color.BLACK;
    }                                       
 
    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        col = Color.WHITE;
    }                                       
 
    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        d = Integer.parseInt(jTextField1.getText().trim());
    }                                          
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Ex1_Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Ex1_Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Ex1_Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Ex1_Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Ex1_Chat().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private java.awt.Canvas canvas1;
    private javax.swing.JTextField chat;
    private javax.swing.JTextField hostv;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextArea msgView;
    private javax.swing.JLabel nick;
    private javax.swing.JTextField nickNamev;
    private javax.swing.JPanel p1;
    private javax.swing.JPanel p2;
    private javax.swing.JTextField portv;
    private javax.swing.JPanel pp;
    // End of variables declaration                  
}


'학원수업 > 자바' 카테고리의 다른 글

학원 46일차 복습(5/23)  (0) 2018.05.23
학원 13일차 복습(3/30)  (0) 2018.03.30
학원 11일차 복습(3/28)  (0) 2018.03.28
학원 10일차 복습(3/27)  (0) 2018.03.27
학원 9일차 복습(3/26)  (0) 2018.03.26

이론


PrintWriter에서이어쓰기  true ,덮어쓰기 (디폴트) false


서버(Server): 사용자들에게 서비스를 제공하는 컴퓨터 

클라이언트(Client): 서버에게 서비스를 요청해서 사용하는 컴퓨터

소켓(socket): TCP를 사용하여 응용 프로그램끼리 통신을 하기 위한 연결 끝점(end point)

ServerSocket 클래스: 서버를 위한 소켓

Socket 클래스: 클라이언트를 위한 소켓



InetAddress는 get매서드를 호출하여서 필요한 InetAddress클래스를 받아서 사용한다. 싱글턴(new로 생성안함)


URL(Uniform Resource Location): 인터넷에서 접근 가능한 자원의 주소를 표현할 수 있는 형식을 의미한다.

입력한 호스트로 URL을 생성하고 URLConnection을 생성

        http://www.hostname.com:8080/mvtest?cmd=1000&n=300

        프로토콜://호스트:포트/파일?쿼리(param=value)

[프로토콜][host][port][path][query]



서버는 요청을 받아서 클라이언트에게 응답 , 연결된 소켓에서 스트림을 생성해서 사용

1.서버로 요청  -> 2. 서버가 요청을 받고  ->  3. 서버가 클라이언트에게 응답 -> 4.서버로부터 응답받음


블로킹메서드:  accept(), readLine();

  


실습


ex1.Ex1_InetAddr

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package ex1;
 
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
 
public class Ex1_InetAddr {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("도메인을 입력 : ");
        String host = sc.nextLine();
        try {
            //getByName(host)입력값을 InetAddress클래스로 생성
            InetAddress[] ia = InetAddress.getAllByName(host);
            for(InetAddress e : ia){
                System.out.println("Host:"+e.getHostAddress());
            }
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
            System.out.println("알수 없는 호스트 입니다.");
        }
         
    }
}

ex1.Ex2_InetAddr

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
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ex1;
 
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
/**
 *
 * @author Linux
 */
public class Ex2_InetAddr extends javax.swing.JFrame {
 
 
    /**
     * Creates new form Ex2_InetAddr
     */
    public Ex2_InetAddr() {
        initComponents();
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        resv = new javax.swing.JTextArea();
        hostv = new javax.swing.JTextField();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jPanel1.setBackground(new java.awt.Color(255, 204, 102));
 
        jLabel1.setFont(new java.awt.Font("굴림", 0, 36)); // NOI18N
        jLabel1.setText("Host :");
 
        jButton1.setText("검색");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
 
        resv.setColumns(20);
        resv.setRows(5);
        jScrollPane1.setViewportView(resv);
 
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(61, 61, 61)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(hostv, javax.swing.GroupLayout.PREFERRED_SIZE, 373, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(35, 35, 35)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 666, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 16, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(hostv, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(31, 31, 31))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(29, 29, 29)))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(33, Short.MAX_VALUE))
        );
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                       
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
         
        try {
            resv.setText(ip(hostv.getText()));
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
        }
         
        
    }                                       
    private String ip(String host) throws UnknownHostException {
        StringBuilder sb = new StringBuilder();
        //InetAddress는 get매서드를 호출하여서 필요한
        //InetAddress클래스를 받아서 사용한다.
        //싱글턴(new로 생성안함)
        InetAddress[] iaArr = InetAddress.getAllByName(host);
        for(InetAddress remote : iaArr){
            sb.append(host).append("IP의 주소는 :").append(remote.getHostAddress()).append("\n");
        }
        return sb.toString();
    }
     
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Ex2_InetAddr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Ex2_InetAddr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Ex2_InetAddr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Ex2_InetAddr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Ex2_InetAddr().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private javax.swing.JTextField hostv;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea resv;
    // End of variables declaration                  
 
}

ex1.Ex1_URL

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
package ex1;
 
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
 
public class Ex1_URL {
    public static void main(String[] args) throws MalformedURLException, IOException {
        Scanner sc = new Scanner(System.in);
        System.out.print("Host:");
        String host = sc.nextLine();
        //입력한 호스트로 URL을 생성하고 URLConnection을 생성
        //프로토콜://호스트:포트/파일?쿼리(param=value)
        URL url = new URL(host);
        URLConnection urlCon = url.openConnection();
        urlCon.connect();
        //해더값을 알아보기 위해서 Map으로 반환
        Map<String, List<String>> map = urlCon.getHeaderFields();
        Set<String> s = map.keySet();
        Iterator<String> iterator= s.iterator();
        while(iterator.hasNext()){
            String next = iterator.next();
            System.out.print(next+" : ");
            List<String> value = map.get(next);
            for(String temp : value){
                System.out.println(temp);
            }
        }//end while
        int len = urlCon.getContentLength();
        System.out.println("문서의 길이 :"+len);
    }
}

ex1.Ex2_InputStreamURL

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
package ex1;
 
//URL(Uniform Resource Location)의 약자
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
 
//인터넷에서 접근 가능한 자원의 주소를 표현할 수 있는 형식을 의미한다.
//[http]://[docs.oracle.com][:80][/javase/8/docs/api/main.jsp][?name=test&id=123]
//[프로토콜][host][port][path][query]
//시나리오 : http://www.naver.com 의 index문서를 읽어와서 화면이 출력하려고 한다.
public class Ex2_InputStreamURL {
    public static void main(String[] args) throws MalformedURLException, IOException {
        //네이버에 url로 접속해주는 URL클래스를 생성해보자.
        URL urlv = new URL(url);
        //접속한 후 네이버의 서버 문서를 스트림으로 읽어오기
        InputStream is = urlv.openStream();
        //MIMETYPE중......
        //서버의 문서의 언어지원 코딩을 클라이언트도 맞추어야 한다.
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "EUC-KR"));
        String str = null;
        while((str = br.readLine()) != null){
            System.out.println(str);
        }
        System.out.println("--------------------------------------------");
        //Scanner를 사용해서 읽어낸다.
        Scanner sc = new Scanner(is,"UTF-8");
        while(sc.hasNext()){
            System.out.println(sc.nextLine());
        }
         
    }
}

ex1.UrlSearching

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
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ex1;
 
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Scanner;
 
/**
 *
 * @author Linux
 */
public class UrlSearching extends javax.swing.JFrame {
 
    ArrayList<String> strAr = new ArrayList<>();
 
    /**
     * Creates new form UrlSearching
     */
    public UrlSearching() {
        initComponents();
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        resv = new javax.swing.JTextArea();
        urlv = new javax.swing.JTextField();
        pathv = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jPanel1.setBackground(new java.awt.Color(255, 255, 204));
 
        jLabel1.setText("URL : ");
 
        jLabel2.setText("Path");
 
        resv.setColumns(20);
        resv.setRows(5);
        jScrollPane1.setViewportView(resv);
 
        jButton1.setText("Search");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
 
        jButton2.setText("save");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
 
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(61, 61, 61)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGap(73, 73, 73)
                                .addComponent(urlv, javax.swing.GroupLayout.PREFERRED_SIZE, 357, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton1)
                                .addGap(17, 17, 17))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGap(58, 58, 58)
                                .addComponent(pathv, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton2)
                                .addGap(34, 34, 34))))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 617, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(50, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(urlv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton1)))
                .addGap(45, 45, 45)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 269, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(pathv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addGap(32, 32, 32))
        );
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                       
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        String url = urlv.getText().trim();
        try {
            URL urlv = new URL(url);
            InputStream is = urlv.openStream();
            URLConnection uc = urlv.openConnection();
            String contype = uc.getContentType();
            //인코딩타입을 가져오기 위해서 split으로 구분!
            String[] ct = contype.split("=");
            System.out.println(contype);
            Scanner sc = new Scanner(is, ct[1]);
            while (sc.hasNext()) {
                resv.append(sc.nextLine() + "\n");
            }
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
 
    }                                       
 
 
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
 
        try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(pathv.getText())), true);) {
            pw.println(resv.getText());
        } catch (IOException ex) {
        }
 
    }                                       
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(UrlSearching.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(UrlSearching.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(UrlSearching.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UrlSearching.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UrlSearching().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField pathv;
    private javax.swing.JTextArea resv;
    private javax.swing.JTextField urlv;
    // End of variables declaration                  
 
}

ex2.Ex1_Server

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
package ex2;
 
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Ex1_Server {
    public Ex1_Server() {
        try (ServerSocket ss = new ServerSocket(9999)) {
            System.out.println("Server Start!!");
            while (true) {
                //클라이언트가 서버에 접속시에 동작하는 메서드
                Socket s = ss.accept();
                System.out.println("Client Connect :" + "" + s.getInetAddress().getHostAddress());
                //서버는 요청을 받아서 클라이언트에게 응답
                //연결된 소켓에서 스트림을 생성해서 사용
                InputStream is = s.getInputStream();
                OutputStream os = s.getOutputStream();
                //2차스트림을 사용해서 개선
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                PrintWriter pw = new PrintWriter(new BufferedOutputStream(os), true);
                //2.번 서버가 요청을 받고
                String msg = br.readLine();
                //3.번 서버가 클라이언트에게 응
                pw.println("ServerMsg :" + msg);
            }
 
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new Ex1_Server();
    }
}

ex2.Ex1_Client

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
package ex2;
 
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Ex1_Client {
 
    public Ex1_Client() {
        try (Socket s = new Socket("192.168.0.118", 9999)) {
            //서버는 요청을 받아서 클라이언트에게 응답
            //연결된 소켓에서 스트림을 생성해서 사용
            InputStream is = s.getInputStream();
            OutputStream os = s.getOutputStream();
            //2차스트림을 사용해서 개선
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            PrintWriter pw = new PrintWriter(new BufferedOutputStream(os), true);
            String msg = "하이";
            pw.println("Client :"+msg);//1.서버로 요청
            String svmsg = br.readLine(); //4.서버로부터 응답받음
            System.out.println(svmsg);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new Ex1_Client();
    }
 
}

ex2.Ex3_Server

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
package ex2;
 
 
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
 
public class Ex3_Server {
 
    private ServerSocket ss;
    private Properties prop;//
 
    public Ex3_Server() {
        try {
            prop = new Properties();//
            ss = new ServerSocket(9999);
            System.out.println("Server Start!");
            // 무한적으로 대기
            while (true) {
                // Client Socket이 접속 되었을 때 동작하는 블록킹 메서드
                Socket s = ss.accept();
                String ip = s.getInetAddress().getHostAddress();
                System.out.println("Server Log 1:" + ip + "에서 접속 했음!");
                while (true) {
                    InputStream is = s.getInputStream();
                    OutputStream os = s.getOutputStream();
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(is));
                    PrintWriter pw = new PrintWriter(
                            new BufferedOutputStream(os), true);
                    String msg = br.readLine();
                    prop.load(new BufferedReader(
                            new FileReader("src/ex2/msg.properties")));//
                    if (msg != null) {
                        System.out.println("Server Log 2:" + msg);
                        StringBuffer sb = new StringBuffer();
                        sb.append("IP:").append(ip).append(":");
                        sb.append(prop.getProperty(msg,
                                "아직 배우지 못한 말입니다.ㅜㅜ"));//
                        pw.println(sb.toString());
                    }
 
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        new Ex3_Server();
    }
 
}

ex2.Ex3_Client

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
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ex2;
 
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
 
/**
 *
 * @author Linux
 */
public class Ex3_Client extends javax.swing.JFrame {
// 클라이언트 소켓 및 스트림 선언
    private Socket s;
    private BufferedReader br;
    private PrintWriter pw;
    public Ex3_Client() {
        try {
            s = new Socket("localhost", 9999);
            //1차 스트림 : 연결된 socket으로 부터 통신을 하기위한 기본 Stream
            InputStream is = s.getInputStream();
            OutputStream os = s.getOutputStream();
            //2차 스트림 : 기능향상
            br = new BufferedReader(new InputStreamReader(is));
            pw = new PrintWriter(
                    new BufferedOutputStream(os), true);
        } catch (IOException ex) {
        }
        initComponents();
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        msgv = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        resv = new javax.swing.JTextArea();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jPanel1.setBackground(new java.awt.Color(255, 255, 204));
 
        jLabel1.setText("MSG:");
 
        msgv.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                msgvActionPerformed(evt);
            }
        });
 
        resv.setColumns(20);
        resv.setRows(5);
        jScrollPane1.setViewportView(resv);
 
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(79, 79, 79)
                        .addComponent(jLabel1)
                        .addGap(67, 67, 67)
                        .addComponent(msgv, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(48, 48, 48)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 659, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(50, 50, 50)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(msgv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                       
 
    private void msgvActionPerformed(java.awt.event.ActionEvent evt) {                                    
          try {
            // 서버로 메시지를 전송
            pw.println(msgv.getText().trim());
            // 받아서 출력
            String serverMsg = br.readLine();
            resv.append(serverMsg + "\n");
        } catch (IOException ex) {
        }
    }                                   
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Ex3_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Ex3_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Ex3_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Ex3_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Ex3_Client().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField msgv;
    private javax.swing.JTextArea resv;
    // End of variables declaration                  
 
}


'학원수업 > 자바' 카테고리의 다른 글

학원 13일차 복습(3/30)  (0) 2018.03.30
학원 12일차 복습(3/29)  (0) 2018.03.30
학원 10일차 복습(3/27)  (0) 2018.03.27
학원 9일차 복습(3/26)  (0) 2018.03.26
학원 8일차 복습(3/23)  (0) 2018.03.23

이론


Adapter디자인패턴을 적용한->MouseAdapter의 원리파악하기

        인터페이스의 추상메서드를 필터링해서 제공해주는 기능

        활용도 Dao의 인터페이스와 같은 곳에서 적용할수 있다.


  synchronized :동시화

    withdraw를 호출하는 스레드가 안전하게 lock pool에서

    작업을 끝낼 때 까지 다른 스레드의 간섭을 받지 않는다.

    작업이 끝나면 당연히 다음 스레드가 이일을 같은 방식으로 진행

    public synchronized void withdraw(int money) { - wait(), notify()

    GUI , Network 상에서 스레드들을 사용하게 됨

    WebApplication에서 스레드에 의해서 자원이 관리가 되기 때문에

    싱글톤 패턴으로 동기화가 적용되어진다.


스레드가 사용하는 공유자원을 각 스레드들이 사용할 때 임계영역이 발생하고, 동시성 문제가 발생된다.


서비스 운영 방식 (standalone 과 xinetd) 

standalone 요청받으면 끊어야한다.

xinetd 끊어지면안됨


포트: 서비스번호


OS->IP->서비스(대기)->데몬


TCP/IP:양방향, UDP:단방향, ICMP, 포트,프로토콜,URL


클라이언트 2.요청 


게이트웨이,DNS,TCP/UDP,IP,URL


서버 1.대기(host,port,protocol)


실습


ex1.Ex5_MultiThread

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
package ex1;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
 
public class Ex5_MultiThread extends JFrame implements Runnable {
//스레드를 구현하는 방법
//run()추상메서드를 재정의하게 된다. 하나의 스레드에게 일을 시키게 프로그래밍을 하도록한다.
 
    private JPanel p1, p2;
    private JButton btn1;
    private JTextArea res;
    private JLabel lb;
    private static boolean inputChk;
    private static boolean status;
 
    public Ex5_MultiThread() {
 
        setTitle("단일 스레드!");
        p1 = new JPanel();
        lb = new JLabel("10초"); //카운트다운에 사용될 라벨..
        p1.add(btn1 = new JButton("click"));
        p1.add(lb);
        add(p1, "North"); //JFrame에 Panel을 붙이는 메서드
        p2 = new JPanel();
        res = new JTextArea(20, 50);
        p2.add(res);
        add(p2);
        setBounds(200, 200, 600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        btn1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //Thread의 생성자의 인자값으로 Runnable을 구현한 클래스의 주소를 전달한다.
                new Thread(Ex5_MultiThread.this).start();
                new Thread() {
                    @Override
                    public void run() {
                        for (int i = 10; i >= 0; i--) {
                            try {
                                if (inputChk) {
                                    lb.setText("Good!");
                                    inputChk = false;
                                    i = 10;
                                    return;
                                } else {
                                    lb.setText(String.valueOf(i) + "초");
                                }
                                Thread.sleep(1000);
                            } catch (InterruptedException ex) {
                                ex.printStackTrace();
                            }
                        }
                        status = true;
                        res.append("=====End======\n");
                    }
                }.start();
            }
        });
    }
 
    public static void main(String[] args) {
        Ex5_MultiThread ref = new Ex5_MultiThread();
    }
 
    @Override
    public void run() {
        String input = JOptionPane.showInputDialog("값을 입력");
        if (!status) {
            res.append("입력한 값" + input + "\n");
            inputChk = true;
        }else{
            res.append("값을 입력 못함\n");
        }
 
    }
 
}

ex1.CanvasDemo

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
package ex1;
 
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
 
public class CanvasDemo extends JFrame implements MouseMotionListener {
 
    private int x, y;
 
    public CanvasDemo() {
        x = 10;
        y = 10;
        Canvas can = new Canvas() {
            //오버라이딩을 해서 캔버스에서 하고 있던 일을 재정의해서 사용!
            @Override
            public void update(Graphics g) {
                paint(g);
            }
 
            @Override
            public void paint(Graphics g) {
                g.setColor(Color.red);
                g.fillOval(x, y, 50, 50);
            }
        };
        add(can);
        //Adapter디자인패턴을 적용한->MouseAdapter의 원리파악하기
        //인터페이스의 추상메서드를 필터링해서 제공해주는 기능
        //활용도 Dao의 인터페이스와 같은 곳에서 적용할수 있다.
        can.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                x =e.getX();
                y =e.getY();
                System.out.println(x+":"+y);
                can.repaint();
                //repaint() -> JVM -> update()호출[캔버스의 화면을 삭제]->paint()호출[그림을 그리는 메서드]
            }
        });
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 500, 500);
        setVisible(true);
    }
    public static void main(String[] args) {
        new CanvasDemo();
    }
 
    @Override
    public void mouseDragged(MouseEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
 
    @Override
    public void mouseMoved(MouseEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
 
}

ex1.Ex3_canvas1

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
package ex1;
 
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
 
public class Ex3_Canvas1 extends JFrame {
 
    private Canvas can;
    private int arcNum;
    private int x = 100;
 
    public int getX() {
        return x;
    }
 
    public void setX(int x) {
        this.x = x;
    }
 
    public Canvas getCan() {
        return can;
    }
 
    public int getArcNum() {
        return arcNum;
    }
 
    public void setArcNum(int arcNum) {
        this.arcNum = arcNum;
    }
 
    public Ex3_Canvas1() throws InterruptedException {
        add(can = new Canvas() {
            @Override
            public void paint(Graphics g) {
                g.setColor(Color.red);
                g.drawArc(x, 100, 100, 100, 0, arcNum);
                 
 
            }
 
            @Override
            public void update(Graphics g) {
                paint(g);
            }
        });
        can.setBackground(Color.white);
        setBounds(100, 100, 800, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //MyThread가 해야할 작업이 현재 클래스의 캔버스를 그리는 일이기 때문에
        //this로 현재객체의 주소값을 전달함
        setVisible(true);
        System.out.println("Test");
        Thread t1 = new Thread(new MyThread0(this));
        Thread t2 = new Thread(new MyThread0(this));
        Thread t3 = new Thread(new MyThread0(this));
         
        t1.start();
        t1.join();
        t2.start();
        t2.join();
        t3.start();
 
    }
 
    public static void main(String[] args) throws InterruptedException {
        new Ex3_Canvas1();
    }
 
}

ex1.MyThread0

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
package ex1;
 
public class MyThread0 implements Runnable {
     
    private Ex3_Canvas1 myCan;
    //생성자 호출시 캔버스를 가지고 있는 객체의 주소값을 초기화
 
    public MyThread0(Ex3_Canvas1 myCan) {
        this.myCan = myCan;
    }
     
    @Override
    public void run() {
        //여기에서 스레드 핸들링 작업(원을 그리기 위한..)
        int temN;
        while (myCan.getArcNum() <= 360) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
           temN = myCan.getArcNum();
            temN = temN + 30;
            myCan.setArcNum(temN);
            myCan.getCan().repaint();//스레드에게 캔버스의 그림을 그리도록 repaint를 호출한다.
        }
        int x = myCan.getX();
        x += 100;
        myCan.setX(x);
        temN =0;
        myCan.setArcNum(temN);
    }
     
}
ex2.Account
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
package ex2;
 
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Account {
    private int balance;
    // synchronized :동시화
    //withdraw를 호출하는 스레드가 안전하게 lock pool에서
    //작업을 끝낼 때 까지 다른 스레드의 간섭을 받지 않는다.
    //작업이 끝나면 당연히 다음 스레드가 이일을 같은 방식으로 진행
    //public synchronized void withdraw(int money) { - wait(), notify()
    //GUI , Network 상에서 스레드들을 사용하게 됨
    //WebApplication에서 스레드에 의해서 자원이 관리가 되기 때문에
    //싱글톤 패턴으로 동기화가 적용되어진다.
    public synchronized void withdraw(int money){
//        synchronized(this){ //동기화 블록
        if(balance>=money){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            balance -=money;
        }
//        }
    }
 
    public int getBalance() {
        return balance;
    }
 
    public void setBalance(int balance) {
        this.balance = balance;
    }
     
}
ex2.Bank
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
package ex2;
 
// 스레드가 사용하는 공유자원을 각 스레드들이 사용할 때
 
import javax.swing.JOptionPane;
 
//임계영역이 발생하고, 동시성 문제가 발생된다.
 
public class Bank extends javax.swing.JFrame implements Runnable{
    private Account acc;
 
    public Bank() {
        acc = new Account();
        initComponents();
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        balance = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        showMoney = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jPanel1.setBackground(new java.awt.Color(255, 204, 102));
 
        jLabel1.setText("예치 금액:");
 
        jButton1.setText("적용");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
 
        showMoney.setText("금액 : 000000");
 
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);
 
        jButton2.setText("인출Start");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
 
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(157, 157, 157)
                        .addComponent(showMoney, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 620, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(balance, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(77, 77, 77)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(78, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(92, 92, 92))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(62, 62, 62)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(balance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(55, 55, 55)
                .addComponent(showMoney, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton2)
                .addContainerGap(36, Short.MAX_VALUE))
        );
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                       
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        //입력한 예치금액을 Account객체로 주입
        try{
        acc.setBalance(Integer.parseInt(balance.getText().trim()));
        showMoney.setText("금액:"+balance.getText().trim());
        }catch(NumberFormatException e){
            JOptionPane.showMessageDialog(Bank.this,"정수만 입력하세요.");
            balance.setText("");
            balance.requestFocus();
        }
    }                                       
 
    //인출버튼 클릭
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        jTextArea1.setText("");
        Thread t1 = new Thread(Bank.this,"Mom");
        Thread t2 = new Thread(Bank.this,"Son");
        t1.start();
        t2.start();
    }                                       
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Bank.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Bank.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Bank.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Bank.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Bank().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private javax.swing.JTextField balance;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JLabel showMoney;
    // End of variables declaration                  
 
     
    //다중스레드가 수행할 작업을 정의
    @Override
    public void run() {
        while(acc.getBalance() >0){
           //메서드가 호출될 때 임의의 수를 선택해서 출금 시킴
           //100,200,300
           int money = (int)(Math.random()*3 +1)*100;
           acc.withdraw(money); //스레드 동시성이 일어남!
           showMoney.setText("금액:"+String.valueOf(acc.getBalance()));
            System.out.println("Current Thread"+Thread.currentThread().getName()+":"+acc.getBalance());
            jTextArea1.append("인출정보 :"+Thread.currentThread().getName()+":"+acc.getBalance()+"\n");
             
             
        }
    }
}

ex3.MyCar

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
package ex3;
 
import java.util.ArrayList;
import java.util.List;
 
public class MyCar {
 
    //생산될 자동차를 저장할 공간
    private List<String> carList;
 
    public MyCar() {
        carList = new ArrayList<>();
    }
 
    //자동차의 이름을 선택(랜덤하게)
    public String getCar() {
        String carName = "";
        switch ((int) (Math.random() * 3)) {
            case 0:
                carName = "그랜저1";
                break;
            case 1:
                carName = "그랜저2";
                break;
            case 2:
                carName = "그랜저3";
                break;
        }
        return carName;
    }
 
    //소비자 패턴!
    public synchronized String pop(Thread t) {
        String carName = "";
        if (carList.size() == 0) {
            try {
                System.out.println("생산된 자동차가 없습니다. VIP룸에서 기다려주세요.");
                wait();
            } catch (InterruptedException ex) {
            }
        }
        carName = carList.remove(carList.size() - 1);
        System.out.println("손님이 차를 구입했습니다.");
        System.out.println("구입한 차이름은 :" + carName + ":" + t.getName());
 
        return carName;
    }
 
    //생산자 패턴
    public synchronized void push(String car, Thread t) {
        carList.add(car);
        System.out.println("자동차가 만들어 졌습니다.");
        if (carList.size() == 5) {
            notify();
        }
    }
 
}

ex3.Producer

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
package ex3;
 
public class Producer implements Runnable {
 
    private MyCar car;
 
    public Producer(MyCar car) {
        this.car = car;
    }
 
    @Override
    public void run() {
        String carName = null;
        for (int i = 0; i < 20; i++) {
            carName = car.getCar();
            Thread t = Thread.currentThread();
            car.push(carName, t);
            try {
                Thread.sleep((int) (Math.random() * 200));
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}

ex3.Customer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package ex3;
 
public class Customer implements Runnable{
    private MyCar car;
 
    public Customer(MyCar car) {
        this.car = car;
    }
     
    @Override
    public void run() {
        String carName = null;
        for (int i = 0; i < 20; i++) {
            carName = car.pop(Thread.currentThread());
            try {
                Thread.sleep((int) (Math.random() * 200));
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}

ex3.ProducerMain

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package ex3;
 
public class ProducerMain {
 
    public static void main(String[] args) {
        MyCar c = new MyCar();
        Producer producer = new Producer(c);
        Thread tPThread = new Thread(producer);
        Customer customer = new Customer(c);
        Thread cCThread = new Thread(customer);
        tPThread.start();
        cCThread.start();
    }
}


'학원수업 > 자바' 카테고리의 다른 글

학원 12일차 복습(3/29)  (0) 2018.03.30
학원 11일차 복습(3/28)  (0) 2018.03.28
학원 9일차 복습(3/26)  (0) 2018.03.26
학원 8일차 복습(3/23)  (0) 2018.03.23
학원 7일차 복습(3/22)  (0) 2018.03.22

이론


한글자 단위로 읽고 쓸수 있는 Reader, Writer계열의 스트림은 내부적으로 버퍼를 내장함

내장된 버퍼는 버퍼가 가득채워질때에만 스트림을 통해서 내보낸다.

flush()는 버퍼가 가득차지 않아도 비우게 한다.


BridgeStream: 바이트 스트림을 문자스트림으로 연결시켜주는 스트림

    

noBridgeStream:   많이 자주 사용 ***** Scanner, PrintWriter


PrintWriter 특징 : autoflush 제공하고

                        println()메서드를 사용해서 한줄단위로 문자열을 전송!

        


StringToken에서 WhiteSpace조차도 인덱스로 취급한다. WhiteSpace를 토큰으로 취급하지 않는다.

StringBuilder sb = new StringBuilder(); //가비지컬렉션의 부담을 줄이기 위해


프로세스 : 프로그램이 실행된 상태
데몬 : 서비스 ,메인스레드에 종속

프로세스의 최소단위: 스레드
스레드 : 별도의 stack 수행

스레드를 상속하는 방법 : extends Thread    
implements Runable
익명내부클래스로 스레드 생성

스레드 생성->스타트메서드호출
start() -> jvm - os의 스케줄러로부터 하나의 스레드를 받아서 ->jvm   --> run()
인터페이스로 구현할때는 start() 메서드가 없으므로 스레드를 새로 생성하고 start해야한다.
생명주기가 끝난 스레드의 주소를 다시 사용할 수 없다.


실습


ex1.Ex1_FileWriteDemo

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
package ex1;
 
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Ex1_FileWriteDemo {
 
    public static void main(String[] args) {
        FileWriter writer = null;
        try {
            //파일에 한 문자 단위로 기록할 수 있는 FileWriter 객체 생성
            writer = new FileWriter("C:\\kosta182\\java\\doc\\song.txt");
            //writer는 문자열을 바로 기록할 수 있다.
            String str = "학교종이 땡땡땡 어서 모이자";
            writer.write(str);
            //한글자 단위로 읽고 쓸수 있는 Reader, Writer계열의 스트림은 내부적으로 버퍼를 내장하
            //내장된 버퍼는 버퍼가 가득채워질때에만 스트림을 통해서 내보낸다.
            //flush()는 버퍼가 가득차지 않아도 비우게 한다.
//            writer.flush();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
 
}

ex1.Ex1_FileReadDemo

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
package ex1;
 
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Ex1_FileReadDemo {
 
    public static void main(String[] args) {
        FileReader reader = null;
 
        try {
            //파일로부터 한문자 단위로 읽어 올수 있는 FileReader 객체 생성
            reader = new FileReader("C:\\kosta182\\java\\doc\\song.txt");
            //스트림을 통해서 읽어들인 유니코드값을 저장할 변수
            int readValue = 0;
            while ((readValue = reader.read()) != -1) {
                System.out.print((char) readValue);
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
 
    }
}

ex1.StringToken

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package ex1;
 
import java.util.StringTokenizer;
 
public class StringToken {
    public static void main(String[] args) {
        String str = "하하/호호//히히/해해/후후";
        //WhiteSpace조차도 인덱스로 취급한다.
        String[] s = str.split("/");
        for(String e : s){
            System.out.println(e);
        }
        System.out.println("==================");
        //WhiteSpace를 토큰으로 취급하지 않는다.
        StringTokenizer stz = new StringTokenizer(str, "/");
        while(stz.hasMoreTokens()){
            String token = stz.nextToken();
            System.out.println(token);
        }
    }
}

ex1.Ex3_Message

1
2
3
4
5
6
7
8
9
10
package ex1;
 
import java.io.IOException;
 
public interface Ex3_Message {
 
    public void addWriter(String msg);
    public String getView();
    public void remove() throws IOException;
}

ex1.Ex3_FileWriter

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
package ex1;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Ex3_FileWriter implements Ex3_Message{
    private String path;
 
    public Ex3_FileWriter() {
        path="C:\\kosta182\\java\\doc\\song.txt";
    }
    @Override
    public void addWriter(String msg) {
        //new FileWriter(path,true) : 문자, 1차스트림
        //생성자의 인자중 두번째인자 append값 (이어쓰기)
        try(BufferedWriter bw =new BufferedWriter(new FileWriter(path, true))){
            bw.write(msg);//버퍼의 내용을 path로 작성
            bw.newLine();//줄바꿈
            bw.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    //res.txt에서 한줄단위(readLine())으로 읽어와서
    //StringBuffer에 저장한 후 String으로 반환하는 메서드
    @Override
    public String getView() {
         
        StringBuilder sb = new StringBuilder(); //가비지컬렉션의 부담을 줄이기 위해
        try(BufferedReader br = new BufferedReader(new FileReader(path))){
            String str = null; //문자열의 끝은 null
            while((str = br.readLine() )!= null){
                sb.append(str).append("\n");
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return sb.toString();
    }
 
    @Override
    public void remove() throws IOException {
        File f = new File(path);
        if(f.delete()){
            f.createNewFile();
        }
    }
     
    public static void main(String[] args) throws IOException{
        //인터페이스를 기준으로 구현객체를 생성
        Ex3_Message ef = new Ex3_FileWriter();
        Scanner sc = new Scanner(System.in);
        while(true){
            System.out.print("1.입력  ,  2.출력  ,  3.삭제 : ");
            String menu = sc.nextLine();
            if(menu.equals("1")){
                System.out.print("MSG: ");
                String msg = sc.nextLine();
                ef.addWriter(msg); //인터페이스의 추상메서드 호출!
            }else if(menu.equals("2")){
                System.out.println(ef.getView());
            }else if(menu.equals("3")){
                //파일을 삭제하고 난 후 새롭게 생성해두면 됩니다.
                ef.remove();
            }else{
                System.out.println("종료 합니다.");
                break;
            }
        }
    }
}

ex1.Ex2_BridgeStream

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
package ex1;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;
 
    //BridgeStream
    //바이트 스트림을 문자스트림으로 연결시켜주는 스트림
    //InputStream으로 연결될때 이것을 문자 스트림으로 변환해서 사용하려고 할때..
    //InputStreamReader, OutputStreamWriter 클래스이다.
public class Ex2_BridgeStream {
    private static String path = "C:\\kosta182\\java\\doc\\data1.txt";
    public static void inputBridege(){
        //키보드: 표준입력 바이트 스트림
        //InputStream is = System.in;
        //파일로 읽어 들인 예제
        try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path)))){
            String msg =null;
            while((msg = br.readLine()) != null){
                System.out.println(msg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
     
    public static void outputBridge(){
        try(BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path)))){
            bw.write("Test입니다");
            bw.newLine();
            bw.flush();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
     
    //noBridgeStream   많이 자주 사용 *****
    public static void useScanner(){
        try(Scanner sc = new Scanner(new BufferedInputStream(new FileInputStream(path)))){
            while(sc.hasNext()){//읽어올 데이터가 있을때 까지
                String msg = sc.nextLine();
                System.out.println(msg);
            }
             
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }
     
    public static void usePrintWriter() throws IOException{
        //PrintWriter 특징 : autoflush 제공하고
        //println()메서드를 사용해서 한줄단위로 문자열을 전송!
        //문자스트림을 연결한 경우
//type1        PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(path, true)),ture)
        //바이트 스트림을 연결한 경우
        PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(path, true)), true);
        //ln은 한줄단위로 데이터를 스트림을 통해서 전송
        pw.println("전송할 문자열!2");
         
    }
    public static void main(String[] args) throws IOException {
        outputBridge();
        inputBridege();
        usePrintWriter();
        inputBridege();
        System.out.println("------------------------");
        useScanner();
        outputBridge();
    }
}

ex2.Ex2.Th1

1
2
3
4
5
6
7
8
9
10
11
12
package ex2;
 
public class Ex2_Th1 extends Thread{
 
    //run메서드를 재정의 해서 스레드에게 시킬동작을 정의해두면 된다.
    @Override
    public void run() {
        //getName() 스레드의 이름을 리턴받아서 출력!
        System.out.println("^-^ :"+getName());
    }
        
}

ex2.Ex2.Th2

1
2
3
4
5
6
7
8
9
10
11
12
13
package ex2;
 
//Runnable 인터페이스를 구현하는 방법
public class Ex2_Th2 implements Runnable{
    //run메서드에서 재정의
    @Override
    public void run() {
//        Thread.currentThread() run을 수행하는 스레드의 주소를 가져옴
         System.out.println("@-@: "+Thread.currentThread().getName()); 
         
    }
 
}

ex2.Ex2.Main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package ex2;
 
public class Ex2_Main {
    //start() -> jvm - os의 스케줄러로부터 하나의 스레드를 받아서 ->jvm   --> run()
    public static void main(String[] args) throws InterruptedException {
        //Thread를 각각 생성
        Ex2_Th1 ref1 = new Ex2_Th1();
        Ex2_Th2 ref2 = new Ex2_Th2();// Runnable 인터페이스를 구현한 클래스
        ref1.start();
        ref1.join(); //join된 스레드가 종료될 때 까지 다른 스레드는 경쟁상태에서 대기한다.
        Thread t = new Thread(ref2);
        //API에서 Runnable을 구현한 인터페이스를 스레드로 생성하도록 오버로딩으로 제공
        t.start();
        for(int i =0; i<20;i++){
            System.out.print("-");
        }
         
    }
}

ex2.ExTestThread

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package ex2;
 
public class ExTestThread extends Thread {
 
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
                System.out.println(i+":"+getName());
            } catch (InterruptedException ex) {
            }
        }
    }
     
    public static void main(String[] args) throws InterruptedException {
        ExTestThread e1 = new ExTestThread();
        e1.start();
        e1.join(3000);
        ExTestThread e2 = new ExTestThread();
        e2.start();
    }
}

ex2.ExTestThread2

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
package ex2;
 
public class ExTestThread2{
    public ExTestThread2() throws InterruptedException{
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for(int i =0; i< 10; i++){
                    Thread.sleep(1000);
                    System.out.println(i+" : "+Thread.currentThread().getName());
                }
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        });
        t1.start();
        t1.join(3000);
        // t1.start(); 생명주기가 끝난 스레드의 주소를 다시 사용할 수 없다.
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for(int i =0; i< 10; i++){
                    Thread.sleep(1000);
                    System.out.println(i+" : "+Thread.currentThread().getName());
                }
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        });
        t2.start();
    }
    public static void main(String[] args) throws InterruptedException {
        new ExTestThread2();
    }
     
}

ex2.Ex3_Main

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
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ex2;
 
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
 
/**
 *
 * @author Linux
 */
public class Ex3_Main extends javax.swing.JFrame {
 
    /**
     * Creates new form Ex3_Main
     */
    public Ex3_Main() {
        initComponents();
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        countdownv = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        resv = new javax.swing.JTextArea();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jPanel1.setBackground(new java.awt.Color(153, 153, 153));
 
        jPanel2.setBackground(new java.awt.Color(255, 153, 153));
 
        jLabel1.setFont(new java.awt.Font("굴림", 0, 24)); // NOI18N
        jLabel1.setText("입력 :");
 
        jButton1.setText("입력 버튼");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
 
        countdownv.setText("10초");
 
        resv.setColumns(20);
        resv.setRows(5);
        jScrollPane1.setViewportView(resv);
 
        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(111, 111, 111)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(106, 106, 106)
                        .addComponent(countdownv, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 747, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(33, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(countdownv))
                .addGap(35, 35, 35)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 373, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(27, Short.MAX_VALUE))
        );
 
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                       
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 10; i >= 0; i--) {
                        System.out.println("i" + i);
                        countdownv.setText(String.valueOf(i) + "초");
                        Thread.sleep(1000);
                    }
                    resv.append("=====END=====\n");
 
                } catch (InterruptedException ex) {
                }
 
            }
        });
 
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                String input = JOptionPane.showInputDialog("값을 입력하세요 :");
                if(t1.isAlive()){
                 
                t1.interrupt();
                countdownv.setText("Good!!");
                }else{
                    resv.append("입력값이 없습니다.\n");
                }
            }
        });
 
        t1.start();
        t2.start();
 
 
    }                                       
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Ex3_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Ex3_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Ex3_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Ex3_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Ex3_Main().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private javax.swing.JLabel countdownv;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea resv;
    // End of variables declaration                  
}


'학원수업 > 자바' 카테고리의 다른 글

학원 11일차 복습(3/28)  (0) 2018.03.28
학원 10일차 복습(3/27)  (0) 2018.03.27
학원 8일차 복습(3/23)  (0) 2018.03.23
학원 7일차 복습(3/22)  (0) 2018.03.22
학원 6일차 복습(3/21)  (0) 2018.03.21

이론


NullPoint예외시 객체생성을 확인하라!


trim() : 문자열 앞뒤 공백을 제거함



Map: key와 value로 저장할 수 있는 자료구조.

Properties: 키와와 값을 String 타입으로 제한한 Map 컬렉션

.properties 파일을 읽어들일때 주로 사용


일차스트림(원시스트림): 장치에 직접 연결가능

이차스트림: 장치에 직접연결할수 없음, 기능을 가지고 있음 ,일차스트림으로 연결시켜줘야함

스트림은 자원이므로 finally에서 close() 해줘야한다.


버퍼: 임시저장소로 사용됨


FileInputStream: 파일로부터 바이트 단위로 읽어 들일 때 사용

FileOutputStream: 파일에 바이트 단위로 데이터를 저장할 때 사용


FileReader: 파일로부터 문자 단위로 읽어 들일 때 사용

FileWriter: 파일에 문자 단위로 데이터를 저장할 때 사용


Data(Input,Output)Stream: 자료형까지 저장할 수 있는 기능을 가진 스트림이다. 반드시 입력했을 때 순서가 매우 중요함 *****

데이터에 저장된 자료형의 순서대로 그대로 메서드를 호출할 것



Serializable : 직렬화 시키는 인터페이스 객체->Data

역직렬화: Data->객체

Serializable 인터페이스 내에서 transient입력시 직렬화 대상에서 제외시킨다.


writeObject(ObjectOutputStream out)

- 직렬화 직전 자동 호출 

     - 추가 직렬화할 내용 작성 가능 


readObject(ObjectInputStream in)

     - 역직렬화 직전 자동 호출

     - 추가 역직렬화 내용 작성 가능


추가 직렬화 및 역직렬화 필요한 경우

     - 부모 클래스가 Serializable 구현하지 않고, 자식 클래스가 Serializable 구현한 경우

     - 부모 필드는 직렬화에서 제외

> writeObject() 에서 부모 필드 직렬화 필요

> readObject()에서 부모 필드 역직렬화 필요

> 부모 클래스가 Serializable 구현하도록 하는 게 제일 쉬움






실습


ex1.Ex5_Map

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
package ex1;
 
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
public class Ex5_Map {
    public static void main(String[] args) {
        String[] msg = {"AA","BB","CC","AA","DD","EE","FF"};
        //key와 value로 저장할 수 있는 자료구조.
        HashMap<Integer, String> map = new HashMap<>();
        int cnt = 0;
        for(String e : msg){
            //put이란 메서드를 사용해서 Map저장한다.
            map.put(cnt+1, e);
            cnt++;
        }
        System.out.println("Size: "+map.size());
        //key는 set구조이기 때문에 중복을 허용하지 않는다.
        Set<Integer> keys = map.keySet();
        for(Integer e : keys){
         //map.get(Key) : Set으로 받아서 키를 추출!
            System.out.println(e);
        }
        //축약형
        //map.entrySet() -> Key, Value 추출
        //Map.Entry<Integer, String> -> key와 value를
        //받아올 인터페이스 자료형
            for(Map.Entry<Integer,String> e : map.entrySet()){
                System.out.println("Key :"+e.getKey());
                System.out.println("Value :"+e.getValue());
            }
         
    }
}

ex1.Ex1_FileOutputStreamDemo

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
package ex1;
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Ex1_FileOutputStreamDemo {
 
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            //파일에 data을 기록할 수 있는 FileOutputStream객체 생성
            //dest.txt파일이 존재하면 덮어쓴다.
            //fos = newFileOutputStream("C:\\kosta182\\java\\doc\\dest.txt");
            //dest.txt파일이 존재하면 이어쓴다.
            fos = new FileOutputStream("C:\\kosta182\\java\\doc\\dest.txt", true);
            //write(int value): 한바이트 기록할 수 있다.
            //value에 해당하는 아스키문자를 기록한다.
            fos.write(66);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

ex1.Ex1_FileInputStreamDemo

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
package ex1;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Ex1_FileInputStreamDemo {
 
    public static void main(String[] args) {
        FileInputStream fis = null;//finally에서 닫아주기 위해서 scope위에 선언
        try {
            //파일로부터 1byte씩 읽어올수 있는 FileInputStream 객체 생성
            //FileInputSteam생성자는 FileNotFoundException을 발생시킨다.
            fis = new FileInputStream("C:\\kosta182\\java\\doc\\hello.txt");
            //스트림을 통해서 읽어들인 byte값을 저장할 변수
            int readValue = 0;
            //스트림의 read()메소드는 읽어들인 byte값을 반환하고
            //파일의 끝에 도달하면 -1을 반환한다.
            while ((readValue = fis.read()) != -1) {
                char ch = (char) readValue;
                System.out.print(ch);
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

ex1.Ex1_FileInputStreamDemo1

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
package ex1;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
public class Ex1_FileInputStreamDemo1 {
 
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            //1바이트씩 이동하게 되면 속도가 늦고 비효율적이므로
            //byte[]을 사용해서 버퍼단위로 파일을 읽어온다.
            byte[] buffer = new byte[1024];
            fis = new FileInputStream("C:\\kosta182\\java\\doc\\hello.txt");
            int readValue = 0;
            while ((readValue = fis.read()) != -1) {
                String str = new String(buffer, 0 , readValue);
                System.out.print(str);
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

ex1.Ex1_TestProperties

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
package ex1;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Ex1_TestProperties {
    private Properties prop;
     
    public Ex1_TestProperties(String keyword) {
        String file ="C:\\kosta182\\java\\workspace\\java0323\\src\\ex1\\msg.properties";
        prop= new Properties();
        try {
            // load메서드가 호출이 될 때 마다 FileInputStream이 생성이 되어서
            // msg.properties파일을 새롭게 로드해온다.
            prop.load(new FileInputStream(file));
            //getProperty(key.default): =>key에 해당하는 값이 있을 경우 반환하지만
            //없으면 기본값을 값으로 사용됨
            String msg = prop.getProperty(keyword, "알수없음");
            System.out.println("읽어온 결과: "+msg);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
         
        System.out.print("Message: ");
        String keyword = sc.nextLine();
        new Ex1_TestProperties(keyword);
    }
}

ex1.Exam1_FileCp

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
package ex1;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Exam1_FileCp {
 
    public static void main(String[] args) {
        // C:\kosta182\java\testdir\jdk.exe 파일을
        // C:\kosta182\java\cpdir 로 복사합니다.
        //주의사항) cpdir이란 폴더나 파일을 수동으로 복사하거나 만들기 금지
        //추가 구현) 복사된 시간을 출력합니다.
        Scanner sc = new Scanner(System.in);
        System.out.print("Case 1 :, Case 2 : [Buffer ] , 3 : [Bufferedl//OStream]");
        int caseNum = Integer.parseInt(sc.nextLine());
        if (caseNum == 1) {
            file1Copy();
        } else if (caseNum == 2) {
            file2Copy();
        } else if (caseNum == 3) {
            file3Copy();
        }
 
    }
 
    private static void file1Copy() {
        System.out.println("파일복사 시작");
        long start = System.currentTimeMillis();
        FileInputStream src = null;
        FileOutputStream dest = null;
        try {
            //원본 파일을 읽기 위한 FileInputStream 객체 생성
            src = new FileInputStream(new File("C:\\kosta182\\java\\testdir\\jdk.exe"));
            //복사본 파일을 생성하기 위한 FileOutputStream 객체 생성
            dest = new FileOutputStream(new File("C:\\kosta182\\java\\cpdir\\jdk2.exe"));
            //FileInputStream을 통해서 읽어들인 값을 지정할 변수
            int readValue = 0;
            //FileInputStream의 read()메소드를 통해서 읽어들인 값을 readValue에 저장
            while ((readValue = src.read()) != -1) {
                //readValue에 저장된 값을 FileOutputStream의 write()메소드를 통해서 파일에 기록
                dest.write(readValue);
            }
 
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally{
            try {
                if(dest != null){
                dest.close();
                }
                if(src != null){
                src.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        long end = System.currentTimeMillis();
        long copyTime = (end -start) /1000;
        System.out.println("걸린시간: "+copyTime+"초");
    }
 
   private static void file2Copy() {
        System.out.println("파일복사 시작");
        long start = System.currentTimeMillis();
        FileInputStream src = null;
        FileOutputStream dest = null;
        try {
            //원본 파일을 읽기 위한 FileInputStream 객체 생성
            src = new FileInputStream(new File("C:\\kosta182\\java\\testdir\\jdk.exe"));
            //복사본 파일을 생성하기 위한 FileOutputStream 객체 생성
            dest = new FileOutputStream(new File("C:\\kosta182\\java\\cpdir\\jdk3.exe"));
            int length = 0;
            //임시저장소로 사용될 byte[]배열 선언
            byte[] buffer = new byte[1024 * 8];
            //FileInputStream의 read()메소드를 통해서 읽어들인 값을 readValue에 저장
            while ((length = src.read(buffer)) != -1) {
                dest.write(buffer, 0 ,length);
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally{
            try {
                if(dest != null){
                dest.close();
                }
                if(src != null){
                src.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        long end = System.currentTimeMillis();
        long copyTime = (end -start) /1000;
        System.out.println("걸린시간: "+copyTime+"초");
    }
 
     private static void file3Copy() {
        System.out.println("파일복사 시작");
        long start = System.currentTimeMillis();
//        FileInputStream src = null;
//        FileOutputStream dest = null;
          BufferedInputStream bis = null;
          BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream("C:\\kosta182\\java\\testdir\\jdk.exe"), 1024 *8);
            bos = new BufferedOutputStream(new FileOutputStream(new File("C:\\kosta182\\java\\cpdir\\jdk4.exe")), 1024 * 8);
            int length= 0;
            while((length = bis.read()) != -1){
                bos.write(length);
            }
            bos.flush(); // 반드시 버퍼의 내용을 비워주는 메서드 호출!
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally{
            try {
                if(bis != null){
                bis.close();
                }
                if( bos != null){
                bos.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        long end = System.currentTimeMillis();
        long copyTime = (end -start) /1000;
        System.out.println("걸린시간: "+copyTime+"초");
    }
}

ex1.Ex2_FileDemo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package ex1;
 
import java.io.File;
import java.util.Scanner;
 
public class Ex2_FileDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Path: ");
        String path = sc.nextLine();
        //C:\kosta182\java
            File directory = new File(path);
            if(directory.exists()){
                if(directory.isDirectory()){
                    //현재 디렉토리내의 모든 파일 디렉토리의 이름 얻기
                    String[] fileNameList = directory.list();
                    for(String fileName : fileNameList){
                        System.out.println("파일이름: "+fileName);
                    }
                }
            }
    }
}

ex1.Exam3_FileDemo

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
package ex1;
 
import java.io.File;
import java.util.Scanner;
 
public class Exam3_FileDemo {
 
    public static void main(String[] args) {//파일과 디렉토리를 구분해서 출력하기
        Scanner sc = new Scanner(System.in);
        System.out.print("Path: ");
        String path = sc.nextLine();
        //C:\kosta182\java
        File directory = new File(path);
        if (directory.exists()) {
            if (directory.isDirectory()) {
                //현재 디렉토리내의 모든 파일 디렉토리의 이름 얻기
                File[] fileNameList = directory.listFiles();
                for (File fileName : fileNameList) {
                    if (fileName.isDirectory()) {
                        System.out.println("디렉토리이름: " + fileName.getName());
                    }else{
                        System.out.println("파일이름: " + fileName.getName());
                    }
                     
                }
            }
        }
    }
    }

ex1.Ex2_FileSearch

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
package ex1;
 
import java.io.File;
import java.util.ArrayList;
 
 
public class Ex2_FileSearch extends javax.swing.JFrame {
 
     
    public Ex2_FileSearch() {
        initComponents();
        
    }
 
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        searchv = new java.awt.TextField();
        btn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        resv = new javax.swing.JTextArea();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jPanel1.setBackground(new java.awt.Color(204, 255, 204));
 
        jLabel1.setText("검색 :");
 
        btn.setText("Search");
        btn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActionPerformed(evt);
            }
        });
 
        resv.setColumns(20);
        resv.setRows(5);
        jScrollPane1.setViewportView(resv);
 
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(109, 109, 109)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addComponent(searchv, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(88, 88, 88)
                        .addComponent(btn))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 674, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(26, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btn, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(searchv, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(48, 48, 48)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
                .addContainerGap())
        );
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                       
 
    private void btnActionPerformed(java.awt.event.ActionEvent evt) {                                   
        resv.setText("");//초기화
        // trim() : String의 문자열의 좌우 공백을 제거하는 메서드
        String path = searchv.getText().trim();
        ArrayList<String> ar = getPathList(path);
        for(String e : ar){
            resv.append(e+"\n");
        }
    }                                  
 
     
    /**
     * @param args the command line arguments
     */
     
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Ex2_FileSearch.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Ex2_FileSearch.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Ex2_FileSearch.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Ex2_FileSearch.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Ex2_FileSearch().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private javax.swing.JButton btn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea resv;
    private java.awt.TextField searchv;
    // End of variables declaration                  
 
    private ArrayList<String> getPathList(String path) {
        ArrayList<String> arlist = new ArrayList<>();
        File directory = new File(path);
        if(directory.exists()){
                if(directory.isDirectory()){
                    //현재 디렉토리내의 모든 파일 디렉토리의 이름 얻기
                    File[] fileNameList = directory.listFiles();
                    for(File e : fileNameList){
                        if(e.isDirectory()){
                            arlist.add("[디렉토리] :"+e.getName());
                        }else{
                            arlist.add("[파일] :"+e.getName());
                        }
                    }
                }
            }
        return arlist;
    }
}

ex1.DataOutputDemo

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
package ex1;
 
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
//자료형까지 저장할 수 있는 기능을 가진 스트림이다.
//반드시 입력했을 때 순서가 매우 중요함 *****
public class Ex1_DataOutputDemo {
 
    public static void main(String[] args) {
        //public interface Closeable extends Autocloseable가 자동으로  close를 해준다. jdk7부터 활용가능
        try {
            DataOutputStream dos = new DataOutputStream(new FileOutputStream("C:\\kosta182\\java\\doc\\test.txt"));
            dos.writeInt(10);
            dos.writeUTF("Test!");
            dos.writeChar('A');
            dos.writeBoolean(true);
            dos.writeFloat(10.5F);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

ex1.DataInputDemo

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
package ex1;
 
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Ex1_DataInputDemo {
 
    //데이터에 저장된 자료형의 순서대로 그대로 메서드를 호출할 것
    public static void main(String[] args) {
        try (DataInputStream dis = new DataInputStream(new FileInputStream("C:\\kosta182\\java\\doc\\test.txt"))) {
            int num = dis.readInt();
            String msg = dis.readUTF();
            char ch = dis.readChar();
            boolean bb = dis.readBoolean();
            float ff = dis.readFloat();
            System.out.println("num : "+num);
            System.out.println("msg : "+msg);
            System.out.println("ch : "+ch);
            System.out.println("bb : "+bb);
            System.out.println("ff : "+ff);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

ex1.Data

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
package ex1;
import java.io.Serializable;
//ObjectStream으로 전송될 객체는 반드시 Serializable 이란 인터페이스를 구현하고 있어야 한다.
//transient: 직렬화 대상에서 제외시킨다.
public class Data implements Serializable{
    private int no;
    transient private String name;
    private String mail;
 
    public int getNo() {
        return no;
    }
 
    public void setNo(int no) {
        this.no = no;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getMail() {
        return mail;
    }
 
    public void setMail(String mail) {
        this.mail = mail;
    }
     
}

ex1.Ex2.ObjectOutputStreamDemo

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
package ex1;
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Ex2_ObjectOutputStreamDemo {
 
    public static void main(String[] args) {
        //메모리에 생성된 객체를 직렬화해서 스트림을 통해 기록할 수 있는
        //ObjectOutPutSteam 객체 생성
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\kosta182\\java\\doc\\obj.sav"))) {
            //ObjectOutputSteam을 통해서 직렬화된 후 파일로 기록될 Data객체생성
            //Data클래스는 반드시 serializable을 구현하고 있어야 한다.
            Data data = new Data();
            data.setNo(33);
            data.setName("홍길동");
            data.setMail("hong@nate.com");
            //ObjectOutputStream객체를 직렬화해서 스트림을 통해 기록할수 있는 writeObject()메소드를 제공한다.
            oos.writeObject(data);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

ex1.Ex2.ObjectInputStreamDemo

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
package ex1;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Ex2_ObjectInputSteamDemo {
 
    public static void main(String[] args) {
        //파일에 저장된 객체를 읽어들이기 위해 ObjectInputSteam 객체 생성
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\kosta182\\java\\doc\\obj.sav"))) {
            //ObjectInputSteam은 스트림으로부터 읽어들인 직렬화된 객체를 역직렬화해서 객체를 생성할 수 있다.
            //역직렬화할때 필요한 클래스 파일을 찾지 못할 경우 ClassNotFoundException을 발생시킨다.
            Data data = (Data)ois.readObject();
            System.out.println("번호 : "+data.getNo());
            System.out.println("이름 : "+data.getName());
            System.out.println("메일 : "+data.getMail());
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

ex1.KostKo

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
package ex1;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class KostKo extends javax.swing.JFrame {
 
    //1. Map으로 저장하기 위해 멤버필드에 선언
    //private HashMap<String,String> talkMap;
    private Properties prop;
 
    public KostKo() {
        //생성
        //talkMap = new HashMap<>();
        prop = new Properties();
        initComponents();
    }
 
    public String execute(String keyword) throws FileNotFoundException, IOException {
        prop.load(new FileInputStream("C:\\kosta182\\java\\workspace\\java0323\\src\\ex1\\msg.properties"));
        //keyword를 검색해서 있으면 반환하고 없으면 default값을 반환한다.
        String msg = prop.getProperty(keyword, "알수 없음");
        return msg;
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        total = new javax.swing.JLabel();
        msg = new javax.swing.JTextField();
        ans = new javax.swing.JTextField();
        talk = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jPanel1.setBackground(new java.awt.Color(255, 255, 204));
 
        jLabel1.setText("말 가르치기 질문");
 
        jLabel2.setText("답변");
 
        jLabel3.setText("대화하기");
 
        total.setText("Total: 0");
 
        talk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                talkActionPerformed(evt);
            }
        });
 
        jButton1.setText("가르치기");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
 
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);
 
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(78, 78, 78)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(msg, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(total)
                        .addGap(48, 48, 48))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(ans, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(101, 101, 101))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(talk, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(71, 71, 71))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 617, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(36, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(53, 53, 53)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(total)
                    .addComponent(jLabel1)
                    .addComponent(msg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(ans, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addComponent(jButton1)
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(talk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 329, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(28, Short.MAX_VALUE))
        );
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                       
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        //가르치기 버튼을 클릭했을 때
        //prop.clear();
        String keyv = msg.getText().trim();
        String valuev = ans.getText().trim();
        // Map에 등록
        //talkMap.put(keyv, valuev);
        prop.setProperty(keyv, valuev);
        // 라벨에 출력
        total.setText("Total :" + prop.size());
        // properties파일에 등록하기 위한 스트림!
        try (FileOutputStream fis = new FileOutputStream("C:\\kosta182\\java\\workspace\\java0323\\src\\ex1\\msg.properties", true)) {
            {
                //2.입력값을 msg ->key, ans ->value로 Map에 등록
                prop.store(fis, "KostaTalk!");
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
 
 
    }                                       
 
    private void talkActionPerformed(java.awt.event.ActionEvent evt) {                                    
        //3.사용자가 대화하기 위해서 입력한 값과 이미 Map에 등록한 (그동안 가르쳤던 말)을 key값으로
        //비교해서 jTextArea1 출력한다.
        String talkVal = talk.getText().trim();
        try {
            jTextArea1.append("나: " + talkVal + "\n");
            jTextArea1.append("KostKo : " + execute(talkVal) + "\n");
            jTextArea1.append("--------------------------\n");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
 
 
    }                                   
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(KostKo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(KostKo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(KostKo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(KostKo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new KostKo().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private javax.swing.JTextField ans;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField msg;
    private javax.swing.JTextField talk;
    private javax.swing.JLabel total;
    // End of variables declaration                  
 
}



'학원수업 > 자바' 카테고리의 다른 글

학원 10일차 복습(3/27)  (0) 2018.03.27
학원 9일차 복습(3/26)  (0) 2018.03.26
학원 7일차 복습(3/22)  (0) 2018.03.22
학원 6일차 복습(3/21)  (0) 2018.03.21
학원 5일차 복습(3/20)  (0) 2018.03.20

이론


Generic: 객체의 cast를 줄임으로서 불필요한 메모리 낭비를 방지하자는 목적

Collection에 Object형을 사용하지 않고 전용객체로 사용하는 개념!

              JDK5부터 지원, JDK7 버젼부터 생성시 <>로 축약가능!


모든 Collection은 반복자(iterator)를 제공해줌

반복자 객체의 hasNext()와 next() 메소드를 이용하여서 컬렉션의 각 원소들을 접근 하게 된다.


MemberVO: 순수하게 회원의 값만을 가지는 객체


Set구조는 중복을 허용하지 않는다. 중복을 제거하면서 반복자, 향상된 for문에 TreeSet오름차순 정렬을 보장함


event 처리하기 위해서는 이벤트 감지자가 필요하다.

발생하는 이벤트의 종류를 파악한 후 이벤트처리 인터페이스를 구현, 버튼에 이벤트 감지자를 등록 해놔야 한다.


cardLayout 생성해서 이벤트가 발생할 때 마다 자식카드를 호출 하기위함

event처리

입력이 완료된 이후 다음페이지로 이동하기 위해서 card를 호출





실습


ex2.Ex2_Generic

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
package ex2;
 
import java.util.ArrayList;
import java.util.Iterator;
//Collection에 Object형을 사용하지 않고 전용객체로 사용하는 개념!
//JDK5부터 지원!
 
public class Ex2_Generic {
    public static void main(String[] args) {
        //JDK7 버젼부터 생성시 <>로 축약가능!
        ArrayList<String> ar = new ArrayList<>();
        //Generic: 객체의 cast를 줄임으로서 불필요한 메모리 낭비를 방지하자는
        //목적입니다. jdk5부터 지원
        ar.add("Test");
        ar.add("Test");
        ar.add("10");
        for(String e : ar){
            System.out.println(e);
        }
        System.out.println("-----------------");
        //모든 Collection은 반복자를 제공해줌
        Iterator<String> it = ar.iterator();
        while(it.hasNext()){//반복할 데이터값이 있으면 true
            String next = it.next();//요소의 값
            System.out.println(next);
        }
        //연습문제) Integer용 ArrayList를 만들고
        //적절한 값을 저장한 후 향상된 for,Iterator를 사용해서
        //출력해봅시다.
        System.out.println("-----------------");
        ArrayList<Integer> arr2 = new ArrayList<>();
        arr2.add(1000);
        arr2.add(2000);
        arr2.add(3000);
        Iterator<Integer> it2 = arr2.iterator();
         while(it2.hasNext()){
            Integer next = it2.next();
            System.out.println(next);
        }
         System.out.println("-----------------");
         for(Integer e : arr2){
            System.out.println(e);
        }
         
    }
}

ex2.Ex3_MemArray

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
package ex2;
 
import java.util.ArrayList;
 
public class Ex3_MemArray {
    public static void main(String[] args) {
        ArrayList<MemberVO> ar = new ArrayList<>();
        MemberVO v  = new MemberVO();
        v.setId("xman");
        v.setPwd("12");
        v.setAge(10);
        //1명 데이터 기억
        ar.add(v);
        MemberVO v1 = new MemberVO();
        v1.setId("xman1");
        v1.setPwd("12");
        v1.setAge(10);
        //1명 데이터 기억
        ar.add(v1);
        MemberVO v2 = new MemberVO();
        v2.setId("xman2");
        v2.setPwd("92");
        v2.setAge(10);
        //1명 데이터 기억
        ar.add(v2);
        //출력
        for(MemberVO e : ar){
            System.out.println("ID: "+e.getId());
            System.out.println("Age: "+e.getAge());
            System.out.println("------------------");
        }
         
    }
     
}

ex2.MemberVO

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
package ex2;
    //순수하게 회원의 값만을 가지는 객체
public class MemberVO {
    private String id,pwd;
    private int age;
    private boolean status;  //성인true, 미성년 false
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getPwd() {
        return pwd;
    }
 
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public boolean isStatus() {
        return status;
    }
 
    public void setStatus(boolean status) {
        this.status = status;
    }
     
}

ex1.MemberDemo

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
package ex1;
 
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextArea;
 
public class MemberDemo extends javax.swing.JFrame {
    //cardLayout 생성해서 이벤트가 발생할 때 마다 자식카드를 호출 하기위함
    private CardLayout card;
 
    /**
     * Creates new form MemberDemo
     */
    public MemberDemo() {
        initComponents();
        card = (CardLayout) pp.getLayout();
        //event처리
        addBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String msgv = msg.getText();
                jTextArea1.append(msgv+"\n");
                //입력이 완료된 이후 다음페이지로 이동하기 위해서 card를 호출
                card.show(pp, "c2");
            }
        });
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        pp = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        msg = new javax.swing.JTextField();
        addBtn = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        insertBtn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        pp.setLayout(new java.awt.CardLayout());
 
        jPanel1.setBackground(new java.awt.Color(255, 204, 204));
 
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ex1/img/img1.PNG"))); // NOI18N
        jLabel1.setText("jLabel1");
 
        jLabel2.setText("MSG:");
 
        addBtn.setText("입력");
 
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 387, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(msg, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(addBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(25, 25, 25))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(54, 54, 54)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(msg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(addBtn))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 453, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
 
        pp.add(jPanel1, "c1");
 
        jPanel2.setBackground(new java.awt.Color(204, 204, 255));
 
        insertBtn.setText("입력폼");
        insertBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insertBtnActionPerformed(evt);
            }
        });
 
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);
 
        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 592, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
                .addComponent(insertBtn)
                .addGap(31, 31, 31))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(insertBtn)))
                .addGap(31, 31, 31))
        );
 
        pp.add(jPanel2, "c2");
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                       
 
    private void insertBtnActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        card.show(pp, "c1");
    }                                        
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MemberDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MemberDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MemberDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MemberDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MemberDemo().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private javax.swing.JButton addBtn;
    private javax.swing.JButton insertBtn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField msg;
    private javax.swing.JPanel pp;
    // End of variables declaration                  
}

ex1.Ex1_HashSet

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
package ex1;
 
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
 
public class Ex1_HashSet {
    //Set구조는 중복을 허용하지 않는다.
    //중복을 제거하면서 반복자, 향상된 for문에 TreeSet오름차순 정렬을 보장함
    public static void main(String[] args) {
        HashSet<String> h1 = new HashSet<>();
        //TreeSet<String> h1 = new HashSet<>();
        h1.add("C");
        h1.add("ATest");
        h1.add("ATest");
        h1.add("B");
        h1.add("D");
        h1.add("D");
        h1.add("A");
        h1.add("A");
        System.out.println("크기 :"+h1.size());
        System.out.println("A문자 포함여부: "+h1.contains("A"));
        Iterator<String> it1 = h1.iterator();
        while(it1.hasNext()){
            String next = it1.next();
            System.out.println(next);
        }
        System.out.println("-----------------------");
        //향상된 for문으로 출력 해보기
        for(String e : h1){
            System.out.println(e);
        }
        System.out.println("-----------------------");
        //HashSet<Integer> h2 = new TreeSet<>();
        TreeSet<Integer> h2 = new TreeSet<>();
        h2.add(10);
        h2.add(55);
        h2.add(19);
        h2.add(8);
        h2.add(11);
        h2.add(1);
        h2.add(19);
        //Iterator<Integer> it2 = h2.iterator(); //오름차순
       Iterator<Integer> it2 = h2.descendingIterator(); //내림차순
        while(it2.hasNext()){
            Integer next = it2.next();
            System.out.println(next);
        }
         
    }
}

ex1.Ex2_ArrayVsLinked

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
package ex1;
 
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
 
public class Ex2_ArrayVsLinked {
 
    private ArrayList<String> arlist;
    private LinkedList<String> linklist;
 
    public Ex2_ArrayVsLinked() {//생성자로 초기화
        arlist = new ArrayList<>();
        linklist = new LinkedList<>();
 
    }
 
    public long testTime(String type1) {//1,2번에 따른 분류, 소요시간
        long start = System.currentTimeMillis();
        if (type1.equals("1")) {
            exe(arlist);
        } else {
            exe(linklist);
        }
        long end = System.currentTimeMillis();
        return (end - start);
    }
 
//    private void exe(ArrayList<String> list) {
//        for (int i = 0; i < 10000000; i++) {
//            list.add(String.valueOf(i));
//        }
//        System.out.println("arlist :" + list.size());
//    }
//
//    private void exe(LinkedList<String> list) {
//        for (int i = 0; i < 10000000; i++) {
//            list.add(String.valueOf(i));
//        }
//        System.out.println("linklist :" + list.size());
//    }
     private void exe(List<String> list) {
        for (int i = 0; i < 10000000; i++) {
            list.add(String.valueOf(i));
        }
        System.out.println("arlist :" + list.size());
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("1.ArrayList , 2.LinkedList:  ");
        String type = sc.nextLine();
        Ex2_ArrayVsLinked ea = new Ex2_ArrayVsLinked();
        System.out.println("걸린시간: "+ea.testTime(type)+"초");
    }
}

team.MemberInfo

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
package team;
 
public class MemberInfo {
     
    private String id;
    private String pwd;
    private int age;
    private String ssn;
    private boolean adult;//미성년
    private boolean gender;//성별
 
    public MemberInfo(String id, String pwd, int age, String ssn, boolean adult, boolean gender) {
        this.id = id;
        this.pwd = pwd;
        this.age = age;
        this.ssn = ssn;
        this.adult = adult;
        this.gender = gender;
    }
 
    public MemberInfo(String id, String pwd, int age) {
        this.id = id;
        this.pwd = pwd;
        this.age = age;
    }
     
     
 
    public MemberInfo() {
    }
 
    public boolean isAdult() {
        return adult;
    }
 
    public void setAdult(boolean adult) {
        this.adult = adult;
    }
 
    public boolean isGender() {
        return gender;
    }
 
    public void setGender(boolean gender) {
        this.gender = gender;
    }
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getPwd() {
        return pwd;
    }
 
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getSsn() {
        return ssn;
    }
 
    public void setSsn(String ssn) {
        this.ssn = ssn;
    }
 
}

team.MemberList

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
package team;
 
import java.util.ArrayList;
public class MemberList {
    private ArrayList<MemberInfo> memberlist = new ArrayList<>();
 
    public MemberList() {
    }
 
    public void MemberIn(String id, String pwd, int age, String ssn) {
        boolean gender = false;
        boolean adult = false;
        String[] str = ssn.split("-");
 
        //성별 남 false 여 true
        switch (str[1].charAt(0)) {
            case '1':
            case '3':
                gender = false;//남자
                break;
            case '2':
            case '4':
                gender = true;//여자
                break;
        }
         
        //입력받은 나이
        if(age > 18) adult = true;
        else adult = false;
 
        //생성자로 초기화
        MemberInfo mi = new MemberInfo(id, pwd, age, ssn, adult, gender);
        memberlist.add(mi);
    }
 
    public void MemberIn(String id, String pwd, int age) {
        MemberInfo mi = new MemberInfo(id, pwd, age);
        memberlist.add(mi);
    }
     
    //어레이리스트를 한꺼번에 넣는다
    /*
    public MemberInfo getMi() {
        return mi;
    }*/
 
    public ArrayList<MemberInfo> getMemberlist() {
        return memberlist;
    }
 
    public void setMemberlist(ArrayList<MemberInfo> memberlist) {
        this.memberlist = memberlist;
    }
}

team.GuiJoin

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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package team;
 
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
 
 
public class GuiJoin extends javax.swing.JFrame {
 
    //cardLayout 생성해서 이벤트가 발생할때마다
    //자식카드를 호출 하기 위함
    //1.카드 레이아웃 생성한다
    private CardLayout card;
    private MemberInfo mi;
 
    //멤버넣을 리스트 생성
    /**
     * Creates new form MemberDemo
     */
    public GuiJoin() {
        initComponents();
        MemberList list = new MemberList();
        //2.카드에 디자인의 레이아웃값을 준다
        card = (CardLayout) pp.getLayout();
         
        //입력 버튼, GUI에서 값을 입력하고 리스트에 추가
        addBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                list.MemberIn(id.getText(), pwd.getText(),
                        Integer.parseInt(age.getText()), ssn.getText());
                po.setText("입력되써어...");
            }
        });
 
        //입력 버튼
        addBtn1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //리스트에 추가하는 방법
                if (list.getMemberlist().size() < 1) {
                    System.out.println("내용없음");
                    return;
                }
                jTextArea1.setText("");
                jTextArea1.append("id\t"
                        + "pwd\t"
                        + "age\t"
                        + "성년\t"
                        + "성별(남false 여true)\n");
 
                for (MemberInfo m : list.getMemberlist()) {
                    jTextArea1.append(m.getId() + "\t"
                            + m.getPwd() + "\t"
                            + m.getAge() + "\t"
                            + m.isAdult() + "\t"
                            + m.isGender() + "\n");
                }
 
                //입력이 완료된 이후 다음페이지로 이동하기
                card.show(pp, "card2");
            }
        });
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        pp = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        label1_img = new javax.swing.JLabel();
        label2 = new javax.swing.JLabel();
        id = new javax.swing.JTextField();
        addBtn = new javax.swing.JButton();
        po = new javax.swing.JLabel();
        label4 = new javax.swing.JLabel();
        pwd = new javax.swing.JTextField();
        age = new javax.swing.JTextField();
        ssn = new javax.swing.JTextField();
        label5 = new javax.swing.JLabel();
        label6 = new javax.swing.JLabel();
        addBtn1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        insertBtn = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("보노보노야아");
        setLocation(new java.awt.Point(800, 400));
        setPreferredSize(new java.awt.Dimension(615, 679));
        setResizable(false);
 
        pp.setLayout(new java.awt.CardLayout());
 
        jPanel3.setBackground(new java.awt.Color(204, 204, 255));
        jPanel3.setForeground(new java.awt.Color(204, 204, 204));
        jPanel3.setPreferredSize(new java.awt.Dimension(613, 679));
 
        label1_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/team/bono1.PNG"))); // NOI18N
 
        label2.setText("id");
 
        addBtn.setText("입력");
 
        po.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        po.setText("포로리야아....입력...해애...");
 
        label4.setText("pwd");
 
        pwd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pwdActionPerformed(evt);
            }
        });
 
        label5.setText("ssn");
 
        label6.setText("age");
 
        addBtn1.setText("리스트로");
 
        jLabel1.setText("Member Join");
 
        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(po, javax.swing.GroupLayout.PREFERRED_SIZE, 516, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(addBtn)
                                .addGap(28, 28, 28)
                                .addComponent(addBtn1))
                            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(jPanel3Layout.createSequentialGroup()
                                    .addComponent(label5)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 112, Short.MAX_VALUE)
                                    .addComponent(ssn, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(jPanel3Layout.createSequentialGroup()
                                    .addComponent(label6)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(age, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(label4)
                                        .addComponent(label2))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(id, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE)
                                        .addComponent(pwd)))))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(51, 51, 51)
                .addComponent(label1_img, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(268, 268, 268)
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(label1_img, javax.swing.GroupLayout.PREFERRED_SIZE, 313, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(po)
                .addGap(36, 36, 36)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pwd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(age, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ssn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addBtn)
                    .addComponent(addBtn1))
                .addGap(0, 98, Short.MAX_VALUE))
        );
 
        pp.add(jPanel3, "card1");
 
        jPanel4.setBackground(new java.awt.Color(204, 255, 204));
        jPanel4.setPreferredSize(new java.awt.Dimension(613, 679));
 
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);
 
        insertBtn.setText("입력폼");
        insertBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insertBtnActionPerformed(evt);
            }
        });
 
        jLabel2.setText("Member List");
 
        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(41, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(insertBtn)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 535, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(37, 37, 37))
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(266, 266, 266)
                .addComponent(jLabel2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap(53, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addGap(38, 38, 38)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 499, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(insertBtn)
                .addGap(33, 33, 33))
        );
 
        pp.add(jPanel4, "card2");
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 615, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(pp, javax.swing.GroupLayout.PREFERRED_SIZE, 591, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 690, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(pp, javax.swing.GroupLayout.PREFERRED_SIZE, 670, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
 
        pack();
    }// </editor-fold>                       
 
    private void insertBtnActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        //지워주기
        id.setText("");
        pwd.setText("");
        age.setText("");
        ssn.setText("");
        po.setText("포로리야..입력해...");
        card.show(pp, "card1");
    }                                        
 
    private void pwdActionPerformed(java.awt.event.ActionEvent evt) {                                   
        // TODO add your handling code here:
    }                                  
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        ArrayList<MemberInfo> mi = new ArrayList<MemberInfo>();
        //card.show(pp, "card3");
 
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GuiJoin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GuiJoin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GuiJoin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GuiJoin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GuiJoin().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private javax.swing.JButton addBtn;
    private javax.swing.JButton addBtn1;
    private javax.swing.JTextField age;
    private javax.swing.JTextField id;
    private javax.swing.JButton insertBtn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JLabel label1_img;
    private javax.swing.JLabel label2;
    private javax.swing.JLabel label4;
    private javax.swing.JLabel label5;
    private javax.swing.JLabel label6;
    private javax.swing.JLabel po;
    private javax.swing.JPanel pp;
    private javax.swing.JTextField pwd;
    private javax.swing.JTextField ssn;
    // End of variables declaration                  
}//클래스의 끝

team.ConsoleJoin

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
package team;
 
import java.util.ArrayList;
import java.util.Scanner;
 
public class ConsoleJoin{
 
    public static void excute() {
        MemberList list = new MemberList();
        String id,pwd;
        int age;
        while (true) {
            System.out.print("메뉴 1 - 입력, 2 - 출력, 3 - 종료: ");
            Scanner sc = new Scanner(System.in);
            int menuNum = Integer.parseInt(sc.nextLine());
            if (menuNum == 1) {
                System.out.print("ID: ");
                id= sc.nextLine();
                System.out.print("PWD: ");
                pwd= sc.nextLine();
                System.out.print("AGE: ");
                age =Integer.parseInt(sc.nextLine());
                list.MemberIn(id, pwd, age);
                System.out.println("현재 총 회원: "+list.getMemberlist().size());
 
            } else if (menuNum == 2) {
                for (MemberInfo e : list.getMemberlist()) {
                    System.out.println("ID: " + e.getId());
                    System.out.println("PWD: " + e.getPwd());
                    System.out.println("AGE: " + e.getAge());
                    System.out.println("--------------------");
                }
            } else if (menuNum == 3) {
                System.out.println("종료되었습니다.");
                break;
            } else {
                System.out.println("잘못된 입력입니다.");
            }
 
 
        }
    }
 
    public static void main(String[] args) {
        excute(); //static 메서드 호출
    }
}

'학원수업 > 자바' 카테고리의 다른 글

학원 9일차 복습(3/26)  (0) 2018.03.26
학원 8일차 복습(3/23)  (0) 2018.03.23
학원 6일차 복습(3/21)  (0) 2018.03.21
학원 5일차 복습(3/20)  (0) 2018.03.20
학원 4일차 복습(3/19)  (0) 2018.03.19

이론


오류의 종류: 에러,예외

예외의 종류: 컴파일 예외, 런타임예외

예외(exception): 잘못된 코드, 부정확한 데이터, 예외적인 상황에 의하여 발생하는 오류

예외 처리: try-catch-finally , throws

오류가 발생하였건 발생하지 않았건 항상 실행되어야 하는 코드는 finally 블록에 넣을 수 있다.


throws: 예외 떠넘기기

getMessage(): 예외 발생시킬 때 생성자 매개값으로 사용한 메시지 리턴

printStackTrace(): 예외 발생 코드 추적한 내용을 모두 콘솔에 출력 , 오류 찾을 때 유용하게 활용


list:    순서유지, 중복저장

set:    순서X, 중복X, null은 허용

map:    키값가짐, 키는 set을 따름(중복X)





실습


ex1.Ex0_ArrayIndex

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package ex1;
 
import java.util.Scanner;
 
public class Ex0_ArrayIndex {
     public static void main(String[] args) {
         Scanner sc = new Scanner(System.in);
         String[] str = new String[3];
        for(int i=0; i<3;i++){
            System.out.print("문자"+(i+1)+":");
            str[i]= sc.nextLine();
        }
         for(int i = 0; i<=str.length; i++){
             System.out.println(str[i]);
             System.out.println("-------------");
         }
    }
 
}

ex1.Ex1.NullPoint

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package ex1;
 
public class Ex1_NullPoint {
    public void test(){
        System.out.println("Test");
    }
    public static void main(String[] args) {
        Ex1_NullPoint en = null;
        try{
            en.test(); //예외가 발생하는 문장, 예외가 발생하면 발생한 실행문에서
                        //catch로 넘어간다.
            System.out.println("테스트가 호출한 이후의 실행문!");
        }catch(NullPointerException e){
            // catch로 간다.
            System.out.println("객체는 생성되어야 한다.");
            //Exception에서 예외메세지 출력
            e.printStackTrace();
        }
         
    }
     
}

ex1.Ex2.ArrayIndexException

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package ex1;
 
import java.util.Scanner;
 
public class Ex2_ArrayIndexException {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("숫자 입력: ");
        String number = sc.nextLine();
        String[] argsv = {"10", number, "30"};
        try{
            for(int i = 0; i<= argsv.length; i++){//1
                int n = Integer.parseInt(argsv[i]);
                System.out.println(n);
                System.out.println("-------------****");//예외발생시 수행안됨!
            }
        }catch(NumberFormatException | ArrayIndexOutOfBoundsException e){
            System.out.println("숫자를 입력 발생");
        }finally{//무조건 실행! 특정 리소스를 반환하는 메서드를 호출할때 사용
            System.out.println("여기는 예외와 상관없이 무조건 수행이됨!");
        }
    }
}

ex1.Ex3.MultiException

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
package ex1;
 
import java.util.Scanner;
 
public class Ex3_MultiException {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("숫자 입력 : ");
        try{
            int number = Integer.parseInt(sc.nextLine());
            int result = 0;
            for (int i = 0; i<10; i++){
                //아래의 예외처리에서 멀티 Exception을 처리하시오.
                result = number / (int)(Math.random()*5);
                System.out.println(result);
            }//for의 마지막
        }catch(NumberFormatException | ArithmeticException e){
            e.printStackTrace();
            //분석, NumberFormatException , ArithmeticException
            // instanceof를 사용해서 같은 메모리영역에(부모,자식,그 해당객체인지)같은 주소인지
            //판별해주는 도구
            if(e instanceof NumberFormatException){
                System.out.println("숫자발생");
            }else{
                System.out.println("예외 발생");
            }
        }catch(Exception e){
            System.out.println("나머지 예외!");
        }// try-catch의 마지막
    }
}

ex1.Ex5.ThrowView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package ex1;
 
public class Ex5_ThrowView {
    public static void main(String[] args) {
        try{
            findClass();
        }catch(ClassNotFoundException ex){
            System.out.println("예외 처리 가능!");
        }
    }
    //-------------------------------------------
    //예) findClass 메서드는 다른 클래스에서 정의되었다고 가정!
    // throws를 사용해서 호출한 곳으로 위임!
    // throws ClassNotFoundException
    public static void findClass() throws ClassNotFoundException{
//        try{
            // forName("") : 문자열로 지정된 경로의 클래스를 불러온다.
         Class clazz = Class.forName("java.lang.String2"); 
//        }catch(ClassNotFoundException ex){
//            System.out.println("예외 형식");
//        }
             
    }
}

ex1.Ex6.UserException

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package ex1;
//사용자 정의 예외처리 extends Exception 상속받아서
//예외를 처리 할 수 도 있다.
public class Ex6_UserException extends Exception{
    private int port = 772;
    public Ex6_UserException(String message){
        super(message); // 부모의 생성자를 호출!
    }
    public Ex6_UserException(String msg, int port){
        super(msg);
        this.port= port;
    }
 
    public int getPort() {
        return port;
    }
     
}

ex1.Ex6.UserExceptionTest

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
package ex1;
 
public class Ex6_UserExceptionTest {
     
    public void test(String[] n) throws Ex6_UserException{
        System.out.println("Test1");
        if(n.length <3){
            //throw는 강제 예외를 생성해서 발생
            //테스트할 때 자주 사용!
                throw new Ex6_UserException("없음");
        }else{
                throw new Ex6_UserException("최종예선",703);
        }
    }
    public static void main(String[] args) {
        Ex6_UserExceptionTest ex = new Ex6_UserExceptionTest();
        try{
            // String API에서 가지고 있는 메서드(반환형이 String 배열)
            // OK/AA/BB-> "/"를 기준으로 배열로 저장해서 반환
            String[] ar = "ok/aa/".split("/");
            System.out.println("ar : length"+ar.length);
            ex.test(ar);
        }catch(Ex6_UserException e){
            e.printStackTrace();
        }
    }
 
}

ex1.exam.Exam1_Exception

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
package ex1.exam;
 
import java.util.Scanner;
 
public class Exam1_Exception {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("숫자 입력 : ");
        try{
            int number = Integer.parseInt(sc.nextLine());
            int result = 0;
            for (int i = 0; i<10; i++){
                result = number / (int)(Math.random()*5);
                System.out.println(result);
            }
        }catch(NumberFormatException e){
            System.out.println("숫자를 입력 발생");
        }catch(ArithmeticException e){
            System.out.println("0으로 나눌수 없습니다.");
        }catch(Exception e){
            System.out.println("알수 없는 예외!");
        }finally{
            System.out.println("여기는 예외와 상관없이 무조건 수행이됨!");
        }
    }
}

ex1.exam.Exam2_Exception

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package ex1.exam;
// throws를 사용해서 예외처리 해보기
 
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Exam2_Exception {
    public static void test() throws ArithmeticException{
        System.out.println(6 / 0);
        System.out.println("냠냠! ");
    }
    public static void main(String[] args) {
        Exam2_Exception ref = new Exam2_Exception();
        try {
            ref.test();
        } catch (ArithmeticException e) {
            System.out.println("0으로 나눌수 없습니다");
        }
    }
     
}

ex2.Ex0.GuiTest

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
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ex2;
 
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
 
/**
 *  event 처리하기 위해서는 이벤트 감지자가 필요하다.
 *  XXListener 인페이스 제공받는다.(추상메서드를 가지고 있기 때문이다.)
 */
//1.발생하는 이벤트의 종류를 파악한 후 이벤트처리 인터페이스를 구현하는 방법
public class Ex0_GuiTest extends javax.swing.JFrame implements ActionListener{
 
    /**
     * Creates new form Ex0_GuiTest
     */
    public Ex0_GuiTest() {
        initComponents(); //GUI객체를 정의하거나 호출한 메서드
        //  3.버튼에 이벤트 감지자를 등록 해놔야 한다.
        // p2의 배경색을 변경
         p2.setBackground(Color.blue);
        btn1.addActionListener(this);
        btn2.addActionListener(this);
        btn3.addActionListener(this);
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        p1 = new javax.swing.JPanel();
        btn1 = new javax.swing.JButton();
        btn2 = new javax.swing.JButton();
        btn3 = new javax.swing.JButton();
        p2 = new javax.swing.JPanel();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        btn1.setBackground(new java.awt.Color(255, 51, 51));
        btn1.setText("Red");
        btn1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn1ActionPerformed(evt);
            }
        });
 
        btn2.setBackground(new java.awt.Color(51, 255, 102));
        btn2.setText("Green");
 
        btn3.setBackground(new java.awt.Color(102, 255, 255));
        btn3.setText("Blue");
 
        javax.swing.GroupLayout p1Layout = new javax.swing.GroupLayout(p1);
        p1.setLayout(p1Layout);
        p1Layout.setHorizontalGroup(
            p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(p1Layout.createSequentialGroup()
                .addGap(114, 114, 114)
                .addComponent(btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(169, 169, 169)
                .addComponent(btn2, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 184, Short.MAX_VALUE)
                .addComponent(btn3, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(76, 76, 76))
        );
        p1Layout.setVerticalGroup(
            p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, p1Layout.createSequentialGroup()
                .addContainerGap(40, Short.MAX_VALUE)
                .addGroup(p1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33))
        );
 
        p2.setBackground(new java.awt.Color(255, 255, 0));
 
        javax.swing.GroupLayout p2Layout = new javax.swing.GroupLayout(p2);
        p2.setLayout(p2Layout);
        p2Layout.setHorizontalGroup(
            p2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        p2Layout.setVerticalGroup(
            p2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 312, Short.MAX_VALUE)
        );
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(p1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(p2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(p1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(p2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
 
        pack();
    }// </editor-fold>                       
 
    private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
    }                                   
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Ex0_GuiTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Ex0_GuiTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Ex0_GuiTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Ex0_GuiTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Ex0_GuiTest().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private javax.swing.JButton btn1;
    private javax.swing.JButton btn2;
    private javax.swing.JButton btn3;
    private javax.swing.JPanel p1;
    private javax.swing.JPanel p2;
    // End of variables declaration                  
 
    @Override
    public void actionPerformed(ActionEvent e) {
        // Action이벤트가 발생 한 후 동작될 작업을 이곳에 정의한다.
        System.out.println("click ! 메서드가 호출 되었습니다.");
        //각각의 버튼 감지자에 의해서 클릭 될 때마다 발생하는 ActionEvent의 주소값 e
        //getSource() 선택된 JButton의 주소값을 받아옴
        JButton btn = (JButton) e.getSource();
        if(btn == btn1){
            System.out.println("첫번째 버튼 클릭!!!");
        }else if(btn == btn2){
             System.out.println("두번째 버튼 클릭!!!");
        }else if(btn == btn3){
             System.out.println("세번째 버튼 클릭!!!");
        }
        p2.setBackground(btn.getBackground());
         
    }
}

ex2.Ex0.Num

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
/*
package ex2;
 
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
 
public class Ex0_Num extends javax.swing.JFrame {
 
    /**
     * Creates new form Ex0_Num
     */
    int num;
 
    public Ex0_Num() {
        initComponents();
        //익명내부클래스를 사용해서 이벤트를 처리함!
        btn1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("+ 버튼이 클릭!");
                result.setText("Num:" + (++num));
            }
        });
        btn2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("- 버튼이 클릭!");
                if (num > 0) {
                    result.setText("Num:" + (--num));
                }
            }
        });
 
    }
 
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
 
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        btn1 = new javax.swing.JButton();
        btn2 = new javax.swing.JButton();
        text = new javax.swing.JTextField();
        result = new javax.swing.JLabel();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jPanel1.setBackground(new java.awt.Color(153, 153, 255));
 
        jButton1.setText("입력");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
 
        btn1.setText("+");
 
        btn2.setText("-");
 
        result.setFont(new java.awt.Font("굴림", 0, 24)); // NOI18N
        result.setText("Num:0");
 
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(text, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(61, 61, 61)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(43, 43, 43)
                .addComponent(btn2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(75, 75, 75))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(442, 442, 442)
                .addComponent(result, javax.swing.GroupLayout.PREFERRED_SIZE, 287, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(201, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(71, 71, 71)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(text, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(146, 146, 146)
                .addComponent(result, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(222, Short.MAX_VALUE))
        );
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
 
        pack();
    }// </editor-fold>                       
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
    }                                       
 
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Ex0_Num.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Ex0_Num.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Ex0_Num.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Ex0_Num.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Ex0_Num().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                    
    private javax.swing.JButton btn1;
    private javax.swing.JButton btn2;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel result;
    private javax.swing.JTextField text;
    // End of variables declaration                  
}

ex2.Ex1.ArrayList

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
package ex2;
 
import java.util.ArrayList;
 
public class Ex1_ArrayList {
    public static void main(String[] args) {
        ArrayList ar = new ArrayList();
        System.out.println("사이즈1: "+ar.size());
        //ArrayList에 값을 저장해보기
        ar.add("Test"); //0
        ar.add("Test"); //1
        int num = 200;
        ar.add(num);//2
        Character ch = 'A';
        ar.add(ch);
        ar.add(3.11f);
        ar.add(100L);
        System.out.println("사이즈2: "+ar.size());
        // 배열과 마찬가지로 첫번째 요소의 인덱스는 0이다.
        for(int i = 0; i<ar.size(); i++){
            //get(index)메서드를 사용해서 요소의 값 가져오기
            System.out.println(ar.get(i));
        }
        System.out.println("----------------------");
        //향상된 for문으로 변경해보기
        for(Object e : ar){
            if(e instanceof String){
                System.out.println("Str: "+e);  
            }else if(e instanceof Integer){
                System.out.println("Int: "+e);  
            }else if(e instanceof Character){
                System.out.println("Char: "+e);  
            }else if(e instanceof Float){
                System.out.println("Float: "+e);  
            }else if(e instanceof Long){
                System.out.println("Long: "+e);  
            }
        }
         
 
        for(Object e : ar){
            String str = e.getClass().getTypeName();
            String str2 = e.getClass().getSimpleName();
            System.out.println(str);
            System.out.println("str2: "+str2);
            //substring 문자열 자르는 메서드 *** String 반환
            //lastIndexOf(".") - 마지막 .을 기준으로 문자열의 위치를 반환 - int형
            //java.lang.String
            System.out.println(str.substring(str.lastIndexOf(".")+ 1)+"형 :"+e);
             
        }
            System.out.println("----------------------");
            //String API학습하기..(조별학습)
            String test = "abcdef";
            System.out.println(test.substring(1));
    }
}


'학원수업 > 자바' 카테고리의 다른 글

학원 8일차 복습(3/23)  (0) 2018.03.23
학원 7일차 복습(3/22)  (0) 2018.03.22
학원 5일차 복습(3/20)  (0) 2018.03.20
학원 4일차 복습(3/19)  (0) 2018.03.19
학원 3일차 복습(3/16)  (0) 2018.03.16

+ Recent posts