Java WindowAdapter

2023. 2. 3. 21:41Java

프로젝트 내 src 내 javabasic 패키지 내 Ex5FileMunje.java

package javabasic;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

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

/*
 * [문제] Ex5FileMunje
 * 
 * Ex4번하고 같은 구조로 구현하기
 * 상품명, 수량,단가 입력하면
 * 상품명,수량,단가,총가격 출력하기
 * 종료시 파일에 저장하고(myshop.txt)
 * 처음 실행시 저장된 파일에서 불러오기
 * 버튼은 [상품추가] 버튼
 * 		  [상품삭제] 버튼
 */
public class Ex5FileMunje extends JFrame {

	JTextField txtProduct;
	JTextField txtNumber;
	JTextField txtPrice;

	JTable table;

//	final 키워드를 붙이지 않아도 된다. 왜냐하면 전역변수이면서 인스턴스 변수이기 때문이다.
//	그래서 메모리 저장 하는 영역은 공통 영역이다. 만약에 이 변수가 지역 변수면
//	익명 내부 지역 클래스에서 써야 할 때는 반드시 final 키워드를 붙여주거나
//	변수가 effectively final 이어야 한다.
//	final String fileName = "C:\\java0901\\myshop.txt"; // 정상작동
	String fileName = "C:\\java0901\\myshop.txt"; // 이렇게 해도 된다.

	JButton btnAdd;
	JButton btnDelete;

	DefaultTableModel model;

	String columnName[] = { "상품명", "수량", "단가", "총가격" };

	public Ex5FileMunje(String title) {
		// TODO Auto-generated constructor stub
		super(title);

//		String exLine = "	   		  	";
//		String []eachEx = exLine.split(",");
//		for (String what:eachEx) {
//			System.out.println(what + "추가되었다.");
//		}
//		System.out.println(eachEx[0] + "추가다.");
		
//		String exL = "1234안녕뭐해.ab*-c";
//		String []eachL = exL.split(",");
//		for (String w:eachL) {
//			System.out.println(w + " 가 추가되었다.");
//		}
//		System.out.println(eachL[0]);
//		//System.out.println(eachL[1]); // java.lang.ArrayIndexOutOfBoundsException: 1 이 뜬다.

		this.setBounds(700, 100, 555, 850);// 시작위치x,y,크기 w,h
		// super로 해도 되고 this로 해도 됨 super는 조상
		// this로 해도 상속을 받아서 괜찮음
		// this.getContentPane().setBackground(Color.orange);//프레임위에 있는 패널의 색상 변경
		this.getContentPane().setBackground(new Color(211, 225, 208));// 프레임위에 있는 패널의 색상 변경
		this.setDesign();// 디자인 코드
		this.writeData();
		this.setVisible(true);// 보이게 하기
//		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//프로그램을 종료해주는 메서드
		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				// TODO Auto-generated method stub

				FileWriter fw = null;
				try {
					fw = new FileWriter(fileName);

					for (int i = 0; i < model.getRowCount(); i = i + 1) {
						for (int j = 0; j < model.getColumnCount(); j = j + 1) {
							if (j != (model.getColumnCount() - 1)) {
								fw.write(model.getValueAt(i, j) + ",");
							} else {
								fw.write(model.getValueAt(i, j) + "\n");
							}
						}
					}
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} finally {
					if (fw != null)
						try {
							fw.close();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
				}

				System.exit(0);
				super.windowClosing(e);
			}
		});
	}

	public void setDesign() {
		this.setLayout(null);

		JLabel lbl1 = new JLabel("상품명 : ");
		lbl1.setBounds(20, 20, 100, 30);
		this.add(lbl1);

		txtProduct = new JTextField();
		txtProduct.setBounds(20, 70, 100, 30);
		this.add(txtProduct);

		JLabel lbl2 = new JLabel("수량 : ");
		lbl2.setBounds(140, 20, 100, 30);
		this.add(lbl2);

		txtNumber = new JTextField();
		txtNumber.setBounds(140, 70, 100, 30);
		this.add(txtNumber);

		JLabel lbl3 = new JLabel("단가 : ");
		lbl3.setBounds(260, 20, 100, 30);
		this.add(lbl3);

		txtPrice = new JTextField();
		txtPrice.setBounds(260, 70, 100, 30);
		this.add(txtPrice);

		model = new DefaultTableModel(columnName, 0);
		table = new JTable(model);
		JScrollPane jsp = new JScrollPane(table);
		jsp.setBounds(20, 120, 500, 500);
		this.add(jsp);

		btnAdd = new JButton("상품추가");
		btnAdd.setBounds(20, 640, 100, 30);
		btnAdd.addActionListener(new btnClick());
		this.add(btnAdd);

		btnDelete = new JButton("상품삭제");
		btnDelete.setBounds(140, 640, 100, 30);
		btnDelete.addActionListener(new deleteBtnClick());
		this.add(btnDelete);

	}

	public void writeData() {
		FileReader fr = null;
		BufferedReader br = null;

		try {
			fr = new FileReader(fileName);
			br = new BufferedReader(fr);

			while (true) {
				String line = br.readLine();
				if (line == null)
					break;

				String fData[] = line.split(",");

				model.addRow(fData);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(this, "저장된 파일이 없습니다. 파일을 찾을 수 없습니다. 파일을 저장해주세요");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
				if (fr != null)
					fr.close();
			} catch (IOException e1) {
				// TODO: handle exception
			}
		}
	}

	class btnClick implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			String product = txtProduct.getText();
			String number = txtNumber.getText();
			String price = txtPrice.getText();
			try {
				long totPrice = Integer.parseInt(number) * Long.parseLong(price);
				String data[] = { product, number, price, String.valueOf(totPrice) };

				model.addRow(data);
				txtProduct.setText("");
				txtNumber.setText("");
				txtPrice.setText("");
			} catch (NumberFormatException e1) {
				// TODO: handle exception
				JOptionPane.showMessageDialog(Ex5FileMunje.this, "숫자 아닌 문자를 넣었어요. 다시 입력해주세요.");
				return;
			}

		}
	}

	class deleteBtnClick implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			int index = table.getSelectedRow();
			if (index == -1) {
				JOptionPane.showMessageDialog(Ex5FileMunje.this, "삭제할 상품을 선택하지 않았습니다. 삭제할 상품을 선택해주세요");
			} else {
				model.removeRow(index);
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Ex5FileMunje("");
	}

}

 

 

위의 코드를 본다.

void javax.swing.table.DefaultTableModel.addRow(Object[] rowData)

addRow(Object[] rowData) 메서드는 

모델의 끝에 한 줄을 추가한다.

만약에 Object[] rowData 가 지정되지 않는다면 새로 추가될 새 줄은 null 값들을 포함할 것이다.

줄이 현재 추가되고 있다는 알림이 발생될 것이다.

 

위의 코드를 본다.

String fData[] = line.split(","); 문이 있다.

여기서 String 형인 line 안에 구분자인 "," 가 하나도 없다면

fData[0] 에 문자열 line 내용이 다 들어가서 반환이 된다.

String 형인 line 안에 구분자인 "," 가 한개도 없고 line 내용이 공백으로 채워져 있다면

fData[0] 에 line 내용인 공백문자들이 들어가 반환이 된다.

 

'Java' 카테고리의 다른 글

Java getSource()  (0) 2023.02.05
Java JScrollBar  (0) 2023.02.05
Java DefaultTableModel  (0) 2023.02.03
Java JTable  (1) 2023.02.03
Java JComboBox  (0) 2023.02.03