본문 바로가기
JAVA

Money Changer with CheckBox

by KWONE 2024. 12. 6.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class EX4 extends JFrame{
	private JPanel upPanel;
	private JPanel centerPanel;
	private String[] money= {"오만원","만원","천원","500원","100원","50원","10원","1원"};
	private int[] mn= {50000,10000,1000,500,100,50,10,1};
	private JTextField[] mtf=new JTextField[mn.length];
	private JCheckBox[] mcb=new JCheckBox[mn.length];
	private boolean [] check=new boolean [mn.length];
	
	public EX4() {
		super("Money Changer with CheckBox");
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		Container c = getContentPane();
		setLayout(new BorderLayout());
		
		upPanel= new JPanel() {
			{	
				setBackground(Color.yellow);
				setLayout(new FlowLayout());
				add(new JLabel("금액" ));
				JTextField tf = new JTextField(10);
				JButton btn = new JButton("계산");
				add(tf);
				add(btn);
				btn.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						String input=tf.getText();
						if(input.length()==0) return ;
						int money = Integer.parseInt(input);
						int m;
						for(int i=0;i<mn.length;i++) {
							if(check[i]==true) {
								m=money/mn[i];
								mtf[i].setText(String.valueOf(m));
								if(m>0) money%=mn[i];
								else mtf[i].setText("0");
							}
						}
					}
				});
			}
			
		};
		centerPanel = new JPanel() {
			{
				setBackground(Color.yellow);
				setLayout(new GridLayout(8,3));
				for(int i =0;i<mn.length;i++) {
					mtf[i]=new JTextField(8);
					mcb[i]=new JCheckBox();
					check[i]=false;
					int index = i;
					mcb[i].addItemListener(new ItemListener() {
						public void itemStateChanged(ItemEvent e) {
							check[index] = e.getStateChange() == ItemEvent.SELECTED; // 상태 반영
						}
					});
					add(new JLabel(money[i]));
					add(mtf[i]);
					add(mcb[i]);
				}
			}
		};
		
		c.add(upPanel,BorderLayout.NORTH);
		c.add(centerPanel,BorderLayout.CENTER);
		setVisible(true);
		setSize(300,300);
	}
	public static void main(String[] args) {
		new EX4();
	}
}

'JAVA' 카테고리의 다른 글

Calculator with Swing  (0) 2024.12.06
컬렉션  (1) 2024.09.24
Chapter 05 실습 문제  (0) 2024.08.19
상속 활용 예제  (0) 2024.08.18
Chapter 04 실습 문제  (0) 2024.08.16