요약정리
평가
물품 등록
학생 등록
삭제
조회
수정
오후일과
실시간 채팅 만들기
웹은 콜백이 없음.
근데 여긴 앱이라 필요
오전일과
상속
화면 만들기
exam_cls> Parent.java
정의만 하는 메소드 (추상화 메소드 abstract)
만들면 class앞에도 abstract 붙여줘야함.
package com.example.exam_cls;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public abstract class Parent {
// 변수
private int no = 0;
private String name = "가나다";
// 생성자
public Parent(){
}
public Parent(int no, String name) {
this.no = no;
this.name = name;
}
// 정의만 하는 메소드 추상화 메소드 abstract
public abstract void myPrint();
// 메소드
public void printParent(){
System.out.println("print Parents");
}
public void methodParent(){
System.out.println("Method Parent");
}
}
exam_cls> Child.java

여기서 상속을 하는 이유
부모에는 만들다만 코드와 완성되지 못한
정의만 된 메소들이 존재하면
private Parent parent = new Parent(); 를 못씀.
그래서 클래스에 extends Parent를 추가하고
아래서 부모를 완성 시킨 다음에 씀.
package com.example.exam_cls;
// 자식 클래스
public class Child extends Parent{
@Override
public void myPrint() {
System.out.println("Child Print");
}
public void print(){}
}
app.java
Parent obj = new Child(); // 완성 되어있는 것을 가져옴 child
obj.methodParent(); // 부모
obj.printParent(); // 부모
obj.myPrint(); // 자식(부모가 제공한 라이브러리를 child로 끌고 와서 작성)
요즘 잘 안쓰는 어플리케이션 만들어 볼꺼임(임포트 오류나서 애 많이 먹음.)
example> frame> MyFrame.java
package com.example.frame;
import java.awt.BorderLayout;
import java.awt.HeadlessException;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; //수동으로 입력
// JFrame
public class MyFrame extends JFrame implements ActionListener{
private JMenuBar menuBar = null;
private JMenu item1 = null;
private JMenu item2 = null;
private JMenuItem menu1 = null;
private JMenuItem menu2 = null;
private JMenuItem menu3 = null;
// 생성자 만들기
public MyFrame() {
}
// 생성자 만들기
public MyFrame(String title) throws HeadlessException {
super(title); // 부모의 생성자 호출함.
this.menuBar = new JMenuBar();
this.setJMenuBar(menuBar);
this.item1 = new JMenu("학생");
menuBar.add(item1);
this.menu1 = new JMenuItem("학생등록");
menu1.addActionListener(this);
item1.add(menu1);
this.menu2 = new JMenuItem("학생수정");
menu2.addActionListener(this);
item1.add(menu2);
this.menu3 = new JMenuItem("학생목록");
menu3.addActionListener(this);
item1.add(menu3);
this.item2 = new JMenu("Edit");
menuBar.add(item2);
this.setSize(500, 400);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// 중간부분의 컴포넌트 모두 제거
this.getContentPane().removeAll();
if(e.getSource() == this.menu1) {
MyPanel1 p1 = new MyPanel1();
this.getContentPane().add(p1, BorderLayout.CENTER);
}
else if(e.getSource() == this.menu2) {
this.getContentPane().add(new MyPanel2(), BorderLayout.CENTER);
}
else if(e.getSource() == this.menu3) {
this.getContentPane().add(new MyPanel3(), BorderLayout.CENTER);
}
// 화면 갱신
this.revalidate();
this.repaint();
}
}
extends JFrame
//생성자 2개 만듬
상속하니까 this.에서 함수 다 나옴
메뉴 넣기
import java.awt.event.ActionListener;
수동 추가
(전구)add unimple
이벤트 발생시 자동으로 호출되는 메소드
메뉴바 셋팅
메뉴 아이템을 넣고
학생에 학생 등록, 학생 수정을 눌렀을때
학생 등록이 눌러졌다는건 누가 알까?
학생 등록(MenuItem)이 앎.
this.menu1 = new JMenuItem("학생등록");
menu1.addActionListener(this); << 요거
item1.add(menu1);
e.getSource까지 함
지금까지 인터페이스, 상속까지 한 것임.
여기서 화면 표기 만들 것임(패널)
frame> MyPanel1.java (학생 등록)
extends JPanel
package com.example.frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; //수동으로 입력
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import com.example.entity.Student;
import com.example.service.StudentService;
import com.example.service.StudentServiceImpl;
// 학생 등록
public class MyPanel1 extends JPanel implements ActionListener {
private JButton btn = null;
private JTextArea text = null;
private JLabel lbl = null;
private StudentService service = new StudentServiceImpl();
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.btn) {
// 사용자가 입력한 내용
String inputText = text.getText();
String[] arr = inputText.split(",");
Student student = new Student();
student.setNo(Long.valueOf(arr[0]));
student.setName(arr[1]);
student.setPhone(arr[2]);
int ret = service.insertStudent(student);
if(ret == 1){
JOptionPane.showMessageDialog(this, "등록성공", "성공", JOptionPane.INFORMATION_MESSAGE);
text.setText("");
}
}
}
public MyPanel1() {
super(); // 부모 생성자 호출하기
this.setLayout(null); // setBounds를 이용한 배치
this.lbl = new JLabel("학번, 이름, 연락처");
lbl.setBounds(4, 10, 200, 20); // x,y좌표, 가로크기, 높이
this.text = new JTextArea();
text.setBounds(120, 10, 160, 20);
this.btn = new JButton("등록하기");
btn.addActionListener(this);
btn.setBounds(4, 80, 100, 20);
this.add(lbl); // 패널에 추가
this.add(text); // 패널에 추가
this.add(btn);
}
}
frame> MyPanel2.java (학생 수정)
package com.example.frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; //수동으로 입력
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import com.example.entity.Student;
import com.example.service.StudentService;
import com.example.service.StudentServiceImpl;
// 학생 수정
public class MyPanel2 extends JPanel implements ActionListener {
private JButton btn = null;
private JTextArea text = null;
private JLabel lbl = null;
private StudentService service = new StudentServiceImpl();
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.btn) {
// 사용자가 입력한 내용
String inputText = text.getText();
String[] arr = inputText.split(",");
Student student = new Student();
student.setNo(Long.valueOf(arr[0]));
student.setName(arr[1]);
student.setPhone(arr[2]);
int ret = service.updateStudent(student);
if(ret == 1){
JOptionPane.showMessageDialog(this, "수정성공", "성공", JOptionPane.INFORMATION_MESSAGE);
text.setText("");
}
}
}
public MyPanel2() {
super(); // 부모 생성자 호출하기
this.setLayout(null); // setBounds를 이용한 배치
this.lbl = new JLabel("학번, 이름, 연락처");
lbl.setBounds(4, 10, 200, 20); // x,y좌표, 가로크기, 높이
this.text = new JTextArea();
text.setBounds(120, 10, 160, 20);
this.btn = new JButton("수정하기");
btn.addActionListener(this);
btn.setBounds(4, 80, 100, 20);
this.add(lbl); // 패널에 추가
this.add(text); // 패널에 추가
this.add(btn);
}
}
frame> MyPanel3.java (학생 전체 목록)
package com.example.frame;
import java.awt.BorderLayout;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.example.entity.Student;
import com.example.service.StudentService;
import com.example.service.StudentServiceImpl;
// 학생 전체 목록
public class MyPanel3 extends JPanel{
StudentService service = new StudentServiceImpl();
public MyPanel3() {
super();
JTable table = new JTable();
List<Student> list = service.selectListStudent(1);
// 문제) List<Student> => Object[][]
Object[][] data = new Object[list.size()][4];
for(int i=0; i<list.size(); i++) {
Student obj = list.get(i);
data[i][0] = obj.getNo();
data[i][1] = obj.getName();
data[i][2] = obj.getPhone();
data[i][3] = obj.getRegdate();
}
String[] columnNames = { "학번", "이름", "연락처", "등록일"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table.setModel(model);
this.add(new JScrollPane(table), BorderLayout.CENTER);
}
}
오후일과
채팅을 만들어 볼 것임.
mqtt할것임.
dependency pom.xml 추가
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
example> mqtt> MqttClient.java
package com.example.mqtt;
import javax.swing.JTextArea;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
public class MyMqttClient implements MqttCallback {
// ws://127.0.0.1:1884, tcp://127.0.0.1:1883
private String broker = "tcp://1.234.5.158:11883";
private String clientId = "db200_" + System.currentTimeMillis();
private String userid = "ds606";
private String password = "ds606";
// 전송되는 메시지를 보관하는 방법
private MemoryPersistence persistence = new MemoryPersistence();
private MqttAsyncClient client = null;
// Panel4의 output위치의 객체
private JTextArea output = null;
public MyMqttClient() {
try {
client = new MqttAsyncClient(broker, clientId, persistence);
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(userid);
options.setPassword(password.toCharArray());
options.setCleanSession(true);
client.connect(options);
client.setCallback(this); //1. 객체를 전달함.
System.out.println(this.client);// 접속객체
Thread.sleep(1000);
}
catch(Exception e) {
System.out.println("접속실패");
e.printStackTrace();
}
}
// 구독설정
public void subscribe(JTextArea output) {
this.output = output;
try {
client.subscribe("/ds200/#", 0);
} catch (MqttException e) {
e.printStackTrace();
}
}
// 구독해제
public void unSubscribe() {
try {
client.unsubscribe("/ds200/#");
}
catch(Exception e){
e.printStackTrace();
System.out.println("구독해제 실패");
}
}
// 메시지보내기
public void sendMessage(String msg) {
try {
MqttMessage message = new MqttMessage();
message.setQos(0);
message.setPayload( msg.getBytes() );
client.publish("/ds200/test1", message);
}
catch(Exception e){
e.printStackTrace();
System.out.println("메시지 보내기 실패");
}
}
@Override
public void connectionLost(Throwable arg0) {
System.out.println("연결이 끊김.");
}
@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
System.out.println("메시전 전송 완료.");
}
@Override
public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
System.out.println("메시지 도착" + arg0);
String msg = arg0 + " => " + new String(arg1.getPayload(), "UTF-8") + "\n";
output.setText( msg + output.getText());
}
}
콜백
client.setCallback(this); // 1. 객체를 전달함.
// 이렇게 해놔야 아래서 옳바르게 반응한다는 것이래요
// 나한테 알려달라는 뜻. mymqttclient 스크립트(아래 오버라이드)가 반응하게
웹은 콜백이 없음.
근데 여긴 앱이라 필요
받을때 필요한게 콜백
언제 올지 모르니 implements MqttCallback
화면 만들기 오늘만 하고 안함
example> frame> MyPanel4.java (실시간 채팅)
package com.example.frame;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; //수동으로 입력
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import com.example.mqtt.MyMqttClient;
public class MyPanel4 extends JPanel implements ActionListener{
private JTextArea msg = new JTextArea(1,1); //메세지 입력
private JButton btn = new JButton("전송하기"); //버튼
private JTextArea output = new JTextArea(); // 메시지 표시
private MyMqttClient client = new MyMqttClient(); // broker접속
public MyPanel4(){
super();
client.subscribe(output);//구독하기
this.setLayout(new BorderLayout());
this.msg.setBackground(Color.GRAY);
this.add(msg, BorderLayout.NORTH);
this.btn.addActionListener(this); //이쪽으로 이벤트 통지
this.add(btn, BorderLayout.SOUTH);
this.add(new JScrollPane(output), BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this.btn) {
client.sendMessage(this.msg.getText());
}
}
}
app.java
MyFrame obj = new MyFrame("제목");
'java' 카테고리의 다른 글
42일차 가장 어려웠던 날, 실습 문제(완료) mqtt, item, book, mqtt, ArrayList로 단편적 db, 연동 (0) | 2022.08.23 |
---|---|
국비 코딩 풀스택 수업 40일차 제너릭 클래스, 추상화, cursor, iterator, first, Map, Filters.and, Updates.combine (0) | 2022.08.19 |
39일차 오후 개인 공부(따로 보충) (0) | 2022.08.19 |
국비 코딩 풀스택 수업 39일차 틀린거 많은 날, app제외 실행, 형변환, List사용법 및 개념, entity의 이동(mvc) (0) | 2022.08.18 |
국비 코딩 풀스택 수업 38일차 lombok, static, 서버관리 폴더따로, entity, ArrayList (1) | 2022.08.18 |