IT/Java

java - JFrame 예제 (list에 입력, 출력, 파일출력, 이벤트 처리)

노마드오브 2018. 11. 25. 19:23

*JFrame 예제 - 프로젝트 JBank 

-- bank 잔고, 입금, 출금, list 이벤트 처리


파일 출력 한글깨짐 처리

property > Run/Debug Settings

-Dfile.encoding=MS949




package com.bank;


import java.awt.FlowLayout;

import java.awt.GridLayout;

import java.awt.List;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.ItemEvent;

import java.awt.event.ItemListener;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileWriter;

import java.io.IOException;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Scanner;

import java.util.Set;


import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JTextField;


public class JBank extends JFrame {

HashMap<String, Integer> hm = new HashMap<>();

List list;

public JBank() {

setTitle("Bank");

        setLayout(new GridLayout(1,2));

        JTextField tfName = new JTextField(20);//이름

        JTextField tfBalance = new JTextField(15);//잔액

        JTextField tfMoney = new JTextField(15); //금액

        

        tfBalance.setEditable(false);

        JButton b1 = new JButton("계좌생성");

        JButton b2 = new JButton("예금");

        JButton b3 = new JButton("출금");

        JButton b4 = new JButton("파일로 저장");

        JPanel p1 = new JPanel();

        p1.add(new JLabel("이름"));

        p1.add(tfName);

        JPanel p2 = new JPanel();

        p2.add(new JLabel("잔액"));

        p2.add(tfBalance);

        JPanel p3 = new JPanel();

        p3.add(tfMoney);

        p3.add(new JLabel("원"));

        //JPanel 기본레이아웃은 FlowLayout

        JPanel p4 = new JPanel();

        p4.setLayout(new FlowLayout());

        p4.add(b2);

        p4.add(b3);

        p4.add(b4);

        //왼쪽화면구성

        JPanel p = new JPanel();

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

        p.add(p1);

        p.add(b1);//계좌생성버튼

        p.add(p2);

        p.add(p3);

        p.add(p4);

        //오른쪽 화면 구현

        list = new List(); //java.awt.List 임포트

        //JFrame에 배치

        add(p);  //왼쪽

        add(list); //오른쪽

        

        //파일저장 이벤트

        b4.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

File dir = new File("src\\com\\bank");

File file = new File(dir, "mybank.txt");

try {

FileWriter fw = new FileWriter(file);

Set<String> set = hm.keySet(); 

Iterator<String> it = set.iterator();

while (it.hasNext()) {

String key = it.next(); // 이름 추출

fw.write(key+" "); // 이름을 파일로 보냄

fw.write(hm.get(key)+"\r\n");  // 잔액을 파일로 보냄

}

//fw.flush();

fw.close();

} catch (IOException e1) {

e1.printStackTrace();

}

}

});

        

        setSize(600, 250); //크기지정

        setVisible(true);//화면보이게 설정

        

        load();

        

        //계좌생성 버튼 이벤트

        b1.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

//if (tfName.getText().length() == 0) { return; }

if (tfName.getText().isEmpty()) { return; }

if (hm.containsKey(tfName.getText())) {

new MessageBox("오류!", "이미 등록된 회원입니다");

return;

}

list.add(tfName.getText());

hm.put(tfName.getText(), 0);

}

});

        // 리스트 이벤트

        list.addItemListener(new ItemListener() {

        @Override

public void itemStateChanged(ItemEvent e) {

String name = list.getSelectedItem();

tfName.setText(name);

//잔액표시

tfBalance.setText(hm.get(name).toString());

}

});

        // 예금이벤트

        b2.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

               /*1.리스트에 선택된 계좌 잔액에

                 * 2. 얼마(tfMoney)를 더해

                 * 3. 잔액을 수정

                 */

try {

String name = list.getSelectedItem();

//잔액표시

int money = hm.get(name); // 잔액

//잔액수정

int value = Integer.parseInt(tfMoney.getText()) + money;

hm.put(name, value);

tfBalance.setText(value+"");

tfMoney.setText("");

} catch (NullPointerException e1) {

new MessageBox("오류!!", "계좌를 선택하세요");

} catch (NumberFormatException e2) {

new MessageBox("입력오류!!", "숫자를 입력하세요");

}

}

});

        // 출금이벤트

        b3.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

try {

String name = list.getSelectedItem();

int money = hm.get(name);

int value = money - Integer.parseInt(tfMoney.getText());

if(value<0) {

//System.out.println("잔액부족");

new MessageBox("잔액부족!!!", name + "님 잔액이 부족합니다");

return;

}

hm.put(name, value);

tfBalance.setText(value+"");

tfMoney.setText("");

} catch (NullPointerException e1) {

new MessageBox("오류!!", "계좌를 선택하세요");

} catch (NumberFormatException e2) {

new MessageBox("입력오류!!", "숫자를 입력하세요");

}

}

});

        

}

private void load() {

hm.clear();

File dir = new File("src\\com\\bank");

File file = new File(dir, "mybank.txt");

try {

if (!file.exists()) {

file.createNewFile();

}

Scanner sc = new Scanner(file);

while(sc.hasNext()) {

String key = sc.next();

int value = sc.nextInt();

hm.put(key, value);

list.add(key);

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

new JBank();

}


}





package com.bank;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class MessageBox extends JFrame {

public MessageBox(String title, String msg) {
setTitle(title);
setLayout(new FlowLayout());
JLabel lb = new JLabel(msg);
JButton closeBtn = new JButton("닫기");
add(lb);
add(closeBtn);
closeBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//setVisible(false);
dispose();
}
});
setSize(300, 100);
setVisible(true);
}

}



mybank.txt

a 1000

b 2000

c 3000