<repo_name>f5074/java<file_sep>/src/main/java/practice/awt/Awt01.java
package practice.awt;

import java.awt.Button;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;

import javax.swing.JOptionPane;

public class Awt01 {
	private static String url;
	private static String id;
	private static String password;

	public static void main(String[] args) {

		// 1. Github에 올릴 경우 자신의 계정정보가 노출되지 않도록 항상 주의
		// 2. 아이디와 비밀번호 파일을 따로 만들어서 관리하기 위해 사용
		try {

			// 프로퍼티 객체 생성
			Properties properties = new Properties();

			// 파일 읽기
			properties.load(new FileInputStream("C:\\DEV\\server.ini"));

			// 프로퍼티 값 읽기
			url = properties.getProperty("url");
			id = properties.getProperty("id");
			password = properties.getProperty("password");

		} catch (Exception exception) {

			System.err.println(exception);
			// 파일이 없을 경우나 예외 발생 시 url, id, password 기본 값
			url = "jdbc:mysql://127.0.0.1:3306/university?characterEncoding=UTF-8&serverTimezone=UTC";
			id = "root";
			password = "<PASSWORD>";
		}

		Frame frame = new Frame();
		Label label1 = new Label("No:");
		Label label2 = new Label("Grade:");
		Label label3 = new Label("Subject:");
		Label label4 = new Label("Professor:");
		Label label5 = new Label("year:");
		Label label6 = new Label("semester:");
		Label label7 = new Label("count:");

		final TextField text1 = new TextField(20);
		final TextField text2 = new TextField(20);
		final TextField text3 = new TextField(20);
		final TextField text4 = new TextField(20);
		final TextField text5 = new TextField(20);
		final TextField text6 = new TextField(20);
		final TextField text7 = new TextField(20);
		Button button = new Button("Insert");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					Class.forName("com.mysql.cj.jdbc.Driver");
					Connection connect = DriverManager.getConnection(url, id, password);

					String sql = "INSERT INTO problemm(no,grade,subject,professor,year,semester,count) VALUES (?,?,?,?,?,?,?)";
					PreparedStatement pstmt = connect.prepareStatement(sql);

					pstmt.setString(1, text1.getText());
					pstmt.setString(2, text2.getText());
					pstmt.setString(3, text3.getText());
					pstmt.setString(4, text4.getText());
					pstmt.setString(5, text5.getText());
					pstmt.setString(6, text6.getText());
					pstmt.setString(7, text7.getText());

					int result = pstmt.executeUpdate();
					
					if (result == 1) {
						System.out.println("성공");
						JOptionPane.showMessageDialog(null, "성공");
					} else {
						System.out.println("실패");
						JOptionPane.showMessageDialog(null, "실패");
					}

				} catch (Exception exception) {
					System.err.println(exception);
				}
			}
		});
		Panel panel = new Panel(new GridLayout(8, 2));
		panel.add(label1);
		panel.add(text1);
		panel.add(label2);
		panel.add(text2);
		panel.add(label3);
		panel.add(text3);
		panel.add(label4);
		panel.add(text4);
		panel.add(label5);
		panel.add(text5);
		panel.add(label6);
		panel.add(text6);
		panel.add(label7);
		panel.add(text7);
		panel.add(button);
		frame.add(panel);
		frame.setVisible(true);
		frame.pack();
	}
}
<file_sep>/src/main/java/practice/jdbc/DBConnect.java
package practice.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import practice.classes.PropertiesClass;

public class DBConnect {
	private Connection con;
	private Statement stmt;

	public DBConnect() {
		try {
			
			PropertiesClass propertiesClass = new PropertiesClass();
			
			Class.forName("com.mysql.cj.jdbc.Driver");
			con = DriverManager.getConnection(propertiesClass.url, propertiesClass.id, propertiesClass.password);
			System.out.println("Connection established");
			
			stmt = con.createStatement();

		} catch (Exception exception) {
			System.err.println(exception);
		}

	}
	
	public Statement getStatement() {
		return stmt;
	}
}
<file_sep>/src/main/java/practice/io/Scanner01.java
package practice.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Scanner01 {

	public static void main(String[] args) {

		try {

			// 프로젝트 현재 경로 찾기
			String projectPath = System.getProperty("user.dir");

			// 파일 객체 생성
			File file = new File(projectPath + "\\src\\main\\resources\\check.txt");

			// 스캐너 생성
			Scanner scanner = new Scanner(file);

			// 스캐너의 다음 줄이 없을 때 까지 출력
			while (scanner.hasNextLine()) {
				// 스캐너 한줄 출력
				System.out.println(scanner.nextLine());
			}
		} catch (Exception exception) {
			System.out.println(exception);
		}

	}

}
<file_sep>/src/main/java/practice/awt/table/AwtTable.java
package practice.awt.table;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

public class AwtTable {

	public static void main(String[] args) {

		JFrame frame = new JFrame("참가자 명단");
		frame.setPreferredSize(new Dimension(500, 300));
		frame.setLocation(500, 400);

		Container contentPane = frame.getContentPane();

		String colNames[] = { "이름", "나이", "성별" };
		// Data가 없는 Default Table을 만든다. column는 있기 때문에 아래와 같이 생성.
		DefaultTableModel model = new DefaultTableModel(colNames, 0);
		// spring table 생성
		JTable table = new JTable(model);
		// scrollpanel을 추가
		JScrollPane scrollpane = new JScrollPane(table);
		// table을 frame에 추가
		contentPane.add(scrollpane, BorderLayout.CENTER);

		JPanel panel = new JPanel();
		JTextField tfName = new JTextField(6);
		JTextField tfAge = new JTextField(3);
		JTextField tfSex = new JTextField(2);

		JButton btAdd = new JButton("Add");
		JButton btDel = new JButton("Del");

		// 이벤트를 처리할 class 객체를 생성한다.
		AddButton adaction = new AddButton(table, tfName, tfAge, tfSex);
		DeleteButton rmaction = new DeleteButton(table);
		// 이벤트 처리 객체를 연결한다.
		btAdd.addActionListener(adaction);
		btDel.addActionListener(rmaction);

		panel.add(new JLabel(colNames[0]));
		panel.add(tfName);
		panel.add(new JLabel(colNames[1]));
		panel.add(tfAge);
		panel.add(new JLabel(colNames[2]));
		panel.add(tfSex);

		panel.add(btAdd);
		panel.add(btDel);

		// table을 frame에 추가
		contentPane.add(panel, BorderLayout.SOUTH);

		// 프로그램 종료
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// frame이 화면에 딱 맞도록 처리
		frame.pack();
		// 화면에 표시
		frame.setVisible(true);
	}

} <file_sep>/src/main/java/practice/jdbc/DBEdit.java
package practice.jdbc;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;

public class DBEdit extends JFrame {
	private ResultSet rs = null;
	private Statement stmt = null;

	private JButton[] btn = new JButton[5];
	private JLabel[] label = new JLabel[8];
	private JTextField[] text = new JTextField[8];
	private JTable table;
	private JScrollPane jp = new JScrollPane();
	private JPanel p[] = new JPanel[4];
	private JPanel p2 = new JPanel();

	private String[][] data = new String[100][8];
	private String[] col = { "empno    ", "ename   ", "job         ", "mgr      ", "hiredate", "sal        ",
			"comm     ", "deptno   " };
	private String[] string = { "", "", "", "", "", "", "", "" };

	public DBEdit() {
		super("DBEdit");

		/////////////
		// DB에 연결
		DBConnect connect = new DBConnect();
		stmt = connect.getStatement();

		JPanel p1 = new JPanel();

		p1.setLayout(new GridLayout(5, 1));

		JPanel p3 = new JPanel();

		btn[0] = new JButton("선택");
		btn[1] = new JButton("출력");
		btn[2] = new JButton("입력");
		btn[3] = new JButton("수정");
		btn[4] = new JButton("삭제");

		for (int i = 0; i < 5; i++) {
			btn[i].addActionListener(action);
			p3.add(btn[i]);
		}

		for (int i = 0; i < 8; i++) {
			label[i] = new JLabel(col[i]);
		}
		for (int i = 0; i < 8; i++) {
			text[i] = new JTextField(15);
		}
		for (int i = 0; i < 4; i++) {
			p[i] = new JPanel();
		}

		int j = -1;
		for (int i = 0; i < 8; i++) {

			if (i % 2 == 0) {
				j++;
			}
			p[j].add(label[i]);
			p[j].add(text[i]);
		}

		p1.add(p3);
		p1.add(p[0]);
		p1.add(p[1]);
		p1.add(p[2]);
		p1.add(p[3]);

		table = new JTable(data, col);
		jp = new JScrollPane(table);
		jp.addMouseListener(new MouseAdapter() {
		});

		Container cp = this.getContentPane();
		cp.setLayout(new GridLayout(2, 1));
		cp.add(p1);
		cp.add(jp);

		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setBounds(100, 100, 500, 500);
		setVisible(true);
		showTable();

	}

	public void showTable() {
		table.removeAll();
		try {
			for (int i = 0; i < 100; i++) {
				for (int j = 0; j < 8; j++) {
					data[i][j] = "";
				}
			}
			rs = stmt.executeQuery("select * from university.emp");
			int i = 0;
			while (rs.next()) {
				data[i][0] = rs.getString(1);
				data[i][1] = rs.getString(2);
				data[i][2] = rs.getString(3);
				data[i][3] = rs.getString(4);
				data[i][4] = rs.getString(5);
				data[i][5] = rs.getString(6);
				data[i][6] = rs.getString(7);
				data[i++][7] = rs.getString(8);
			}
			table.repaint();
		} catch (Exception e) {
			System.err.println("보여 주기 에러");
		}
	}

	ActionBtn action = new ActionBtn();

	class ActionBtn extends Exception implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if (e.getActionCommand().equals("출력")) {
				showTable();
			} else if (e.getActionCommand().equals("선택")) {
				int row = table.getSelectedRow();
				/////////////////////
				// 텍스트 필드에 받아온 데이터 보여주기
				for (int i = 0; i < 8; i++) {
					text[i].setText(data[row][i]);
				}
			} else if (e.getActionCommand().equals("입력")) {
				try {
					for (int i = 0; i < 8; i++) {
						if (text[i].getText().equals("")) {

								
						} else {
							string[i] = text[i].getText();
						}
							
					}
					stmt.executeUpdate("insert into university.emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) values('" + string[0] + "','" + string[1] + "' ,'" + string[2]+ "','" + string[3] + "','" + string[4] + "','" + string[5] + "','" + string[6] + "','" + string[7]
							+ "')");
//					stmt.executeQuery("commit");
				} catch (Exception exception) {
					System.err.println(exception.getMessage());
				}
				////////////////////
				// 화면에 출력하기
				showTable();
				for (int i = 0; i < 8; i++) {
					text[i].setText("");
				}
			} else if (e.getActionCommand().equals("수정")) {
				try {
					stmt.executeQuery(
							"update emp set" + " empno = " + text[0].getText() + " ,ename='" + text[1].getText()
									+ "',job='" + text[2].getText() + "',mgr=" + text[3].getText() + ",hiredate='"
									+ text[4].getText() + "',sal=" + text[5].getText() + ",comm=" + text[6].getText()
									+ ",deptno =" + text[7].getText() + "where empno = " + text[0].getText());
					stmt.executeQuery("commit");
				} catch (Exception ex) {
					System.err.println("수정 에러");
				}
				////////////////////
				// 화면에 출력하기
				showTable();
				for (int i = 0; i < 8; i++) {
					text[i].setText("");
				}
			} else if (e.getActionCommand().equals("삭제")) {
				try {
					System.out.println(text[0].getText());
					stmt.executeQuery("delete from emp where" + " empno = " + text[0].getText());
					stmt.executeQuery("commit");
				} catch (Exception ex) {
					System.err.println("삭제 에러");
				}
				////////////////////
				// 화면에 출력하기
				showTable();
				for (int i = 0; i < 8; i++) {
					text[i].setText("");
				}
			}
		}
	}

	public static void main(String[] args) {
		DBEdit db = new DBEdit();
	}
}<file_sep>/src/main/java/practice/classes/Class01.java
package practice.classes;

public class Class01 {

	public Class01() {
		System.out.println("1번으로 클래스 생성");

	}
	
	public Class01(String x) {
		System.out.println("2번으로 클래스 생성");
		System.out.println(x);
	}
	
	void print() {
		System.out.println("print");
	}
}
<file_sep>/src/main/java/practice/awt/table02/TableEx.java
package practice.awt.table02;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JTable;

public class TableEx {

	public static void main(String[] args) {
		
		Frame f = new Frame();
		String[] columnType = { "번호", "이름", "나이", "성별"};

		Object[][] data = {

		       {"1", "김철수", "20", "남성"},

		       {"2", "김옥자", "43", "여성"},

		       {"3", "이순신", "100", "남성"},

		       {"4", "유관순", "18", "여성"},

		       {"5", "이 도", "54", "남성"}

		};

		JTable table = new JTable(data, columnType);
		
		// 종료 이벤트
		f.addWindowListener(new WindowAdapter(){
			  public void windowClosing(WindowEvent we){
			    System.exit(0);
			  }
		});
		
		f.add(table);
		f.setVisible(true);
		f.pack();
	}

}
<file_sep>/src/main/java/practice/awt/table/AddButton.java
package practice.awt.table;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

public class AddButton implements ActionListener {

	JTable table;
	JTextField tfName;
	JTextField tfAge;
	JTextField tfSex;

	// 생성자에게 table과 기타 정보를 넘겨준다.
	public AddButton(JTable table, JTextField tfName, JTextField tfAge, JTextField tfSex) {
		this.table = table;
		this.tfName = tfName;
		this.tfAge = tfAge;
		this.tfSex = tfSex;
	}

	public void actionPerformed(ActionEvent e) {
		String str[] = new String[3];
		str[0] = tfName.getText();
		str[1] = tfAge.getText();
		str[2] = tfSex.getText();

		// 생성자로부터 받은 table 객체의 타입을 변경한다.
		DefaultTableModel model = (DefaultTableModel) table.getModel();
		// table에 object를 추가한다.
		model.addRow(str);
	}
}<file_sep>/src/main/resources/University.emp.sql
-- 문제M
CREATE TABLE `problemm` (
	`no`        VARCHAR(50) NOT NULL COMMENT '일련번호', -- 일련번호
	`grade`     VARCHAR(50) NULL     COMMENT '학년', -- 학년
	`subject`   VARCHAR(50) NULL     COMMENT '과목명', -- 과목명
	`professor` VARCHAR(50) NULL     COMMENT '출제자명', -- 출제자명
	`year`      VARCHAR(50) NULL     COMMENT '년도', -- 년도
	`semester`  VARCHAR(50) NULL     COMMENT '학기', -- 학기
	`count`     VARCHAR(50) NULL     COMMENT '문항수' -- 문항수
)
COMMENT '문제M';

-- 문제M
ALTER TABLE `problemm`
	ADD CONSTRAINT `PK_problemm` -- 문제M 기본키
		PRIMARY KEY (
			`no` -- 일련번호
		);

-- 문제D
CREATE TABLE `problemd` (
	`no`         VARCHAR(50) NOT NULL COMMENT '일련번호', -- 일련번호
	`number`     VARCHAR(50) NULL     COMMENT '문제번호', -- 문제번호
	`contents`   VARCHAR(50) NULL     COMMENT '문제내용', -- 문제내용
	`exno`       VARCHAR(50) NULL     COMMENT '보기번호', -- 보기번호
	`excontents` VARCHAR(50) NULL     COMMENT '보기내용' -- 보기내용
)
COMMENT '문제D';

-- 문제D
ALTER TABLE `problemd`
	ADD CONSTRAINT `PK_problemd` -- 문제D 기본키
		PRIMARY KEY (
			`no` -- 일련번호
		);

-- 문제D
ALTER TABLE `problemd`
	ADD CONSTRAINT `FK_problemm_TO_problemd` -- 문제M -> 문제D
		FOREIGN KEY (
			`no` -- 일련번호
		)
		REFERENCES `problemm` ( -- 문제M
			`no` -- 일련번호
		);<file_sep>/src/main/resources/server.ini
url=127.0.0.1
id=root
password=<PASSWORD>