💬
개인적으로 자바에서 중요하다고 생각되는 예외 처리를 배우지 않고
몇 주째 '자바 스윙'을 수업하고 있다.
프로젝트, 포트폴리오로 활용 한다는데 나는 잘 모르겠다.
정말 실무에서 자바 스윙이 쓰이는지.
자바 스윙에 몇 주간 시간 투자한 만큼 실무에서 활용할 수 있는지 말이다.
배우고 있는 수강생 입장에서는 실무에 대해서 알 수 없지만
배움에 있어서 불필요한 배움은 없다고 생각한다.
이 또한 분명 도움이 될 거라고 생각하고 그저 열심히 배우고 있을 뿐이다.
package jtableform;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class JTable_test01 extends JFrame {
// iv 선언문
DefaultTableModel dtm;
JTable table;
JScrollPane scroll;
JPanel northp, southp, inform, eastp;
JLabel label, laName, laAge, laJob;
JButton btDel, btExit, btInput, btCancel;
JTextField tfName, tfAge, tfJob;
Font font; // 초기 폰트 설정
int srow = -1; // 테이블의 선택된 행 인덱스 값. 테이블 0 레코드
boolean modify = false; // 입력(f)/수정(t) 체크 변수
public JTable_test01() {
setTitle("JTable 테스트");
//테이블 영역에 들어갈 데이터를 2차원 배열로 선언
String[] columnNames = { "이름", "나이", "직업" };
Object[][] rowData =
{
{"홍길동", 13, "학생"},
{"김유신", 15, "화랑"},
{"김덕만", 16, "공주"}
};
northp = new JPanel();
label = new JLabel("Hello 테이블", JLabel.CENTER);
font = new Font("돋움", Font.BOLD, 15);
label.setFont(font); //초기폰트 설정
northp.add(label);
add("North", northp);
InputForm(); //입력폼
//테이블 생성
eastp = new JPanel();
dtm = new DefaultTableModel(rowData, columnNames);
table = new JTable(dtm); //모델에 테이블 연결
scroll = new JScrollPane(table);
table.setAutoCreateRowSorter(true); //컬럼 헤더 클릭하면 자동정렬 해줌
table.setFillsViewportHeight(true);
eastp.add(scroll);
add("East", scroll); //동쪽배치
//아래쪽 JPanel
southp = new JPanel();
btDel = new JButton("삭제");
btExit = new JButton("종료");
southp.add(btDel);
southp.add(btExit);
add("South", southp); //남쪽 배치
table.addMouseListener(new MyAdapter()); //테이블 데이터 클릭시 입력버튼 수정버튼으로 변환
btDel.addActionListener(new MyListner());
btExit.addActionListener(new MyListner());
setBounds(400, 300, 700, 700);
setVisible(true);
}
//폼 하나로 입력폼과 수정폼으로 사용
void InputForm() {
inform = new JPanel();
inform.setLayout(null);
laName = new JLabel("이름");
laAge = new JLabel("나이");
laJob = new JLabel("직업");
tfName = new JTextField();
tfAge = new JTextField();
tfJob = new JTextField();
btInput = new JButton("입력");
btCancel = new JButton("취소");
laName.setBounds(30, 30, 30, 30);
laAge.setBounds(30, 80, 30, 30);
laJob.setBounds(30, 130, 60, 30);
tfName.setBounds(80, 30, 80, 30);
tfAge.setBounds(80, 80, 80, 30);
tfJob.setBounds(80, 130, 80, 30);
btInput.setBounds(30, 190, 60, 30);
btCancel.setBounds(100, 190, 60, 30);
inform.add(laName);
inform.add(laAge);
inform.add(laJob);
inform.add(tfName);
inform.add(tfAge);
inform.add(tfJob);
inform.add(btInput);
inform.add(btCancel);
add("Center", inform); // 서쪽이 아닌 중앙에 배치
btInput.addActionListener(new MyListner());
btCancel.addActionListener(new MyListner());
}
//ActionEvent 내부 클래스로 이벤트 처리기 작성
class MyListner implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object ob = e.getSource(); //getSource() => 이벤트를 발생시킨 객체의 위치값을 가져온다.
//입력폼의 [입력]
if (ob == btInput) {
String name = tfName.getText();
String age = tfAge.getText();
String job = tfJob.getText();
//modify = false 수정
if (!modify) { //[입력]
Object rowData[] = { name, age, job }; //배열에 저장
dtm.addRow(rowData); //모델 테이블 마지막 행에 추가
initTF(); //입력폼 호출
} else {
dtm.setValueAt(name, srow, 0); //setValueAt()는 원하는 위치의 데이터를 변경해주는 메소드
dtm.setValueAt(age, srow, 1);
dtm.setValueAt(job, srow, 2);
initTF();
}
}
modify = false; //입력상태
//입력폼의 [취소]
if (ob == btCancel) {
tfName.setText("");
tfAge.setText("");
tfJob.setText("");
tfName.requestFocus();
}
//폼의 [삭제]
if (ob == btDel) {
String delName = JOptionPane.showInputDialog(null, "삭제할 이름을 입력하세요", "이름");
for (int i = 0; i < table.getRowCount(); i++) {
if (delName.equals(table.getValueAt(i, 0))) {
dtm.removeRow(i); //행 삭제
initTF();
}
}
}
//폼의 [종료]
if (ob == btExit) {
System.exit(0);
}
}
}
//폼 초기화
void initTF() {
tfName.setEditable(true);
tfName.setText("");
tfAge.setText("");
tfJob.setText("");
tfName.requestFocus(); //requestFocus() => 키 이벤트를 받을 컴포넌트를 강제로 설정
btInput.setText("입력");
}
//MouseEvent 내부 클래스로 이벤트 처리기 작성
class MyAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e) { //이벤트 핸들러 메소드
srow = table.getSelectedRow(); //테이블의 선택된 행 인덱스 값
String name = (String) table.getValueAt(srow, 0);
String age = table.getValueAt(srow, 1).toString();
String job = table.getValueAt(srow, 2).toString();
label.setText("이름:" + name + ", 나이: " + age + ", 직업:" + job);
tfName.setText(name);
tfAge.setText(age);
tfJob.setText(job);
//[입력] 버튼 [수정] 버튼으로 바꾸기
modify = true; //수정
btInput.setText("수정");
}
}
public static void main(String[] args) {
new JTable_test01();
}
}
백지 상태에서 다시 입력해 보라고 했을때 후다닥! 입력하는 수준 까지는 아니더라도 어느정도 수준을 올리고 싶어서 코드 일부를 지운 상태에서
하나씩 채워가는 연습을 했다.
아래 사진처럼 말이다.
뇌가 기억을 못 하고 방황하고 있을때 손이 먼저 나서서 입력할 수 있도록
코드작성을 반복적으로 열심히 해야겠다.