정리노트

[자바/java] Swing 연습문제 숫자(UP/DOWN) 게임 본문

프로그래밍/Java

[자바/java] Swing 연습문제 숫자(UP/DOWN) 게임

Rolen 2023. 1. 17. 19:32

JLabel 색상 변경
JLabel 폰트 지정

Keyadapter 상속
사용 이벤트
- 엔터키로 답 전송, 버튼으로 초기화, 종료하기

package q10;
import java.util.Random;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Q10 extends JFrame {
	JLabel l1, l2;
	JTextField tf;
	JButton b1, b2;
	int num;
	Random rd;
	Q10() {
		setSize(400, 200);
		setTitle("UP/DOWN");
		setLayout(null);
		rd = new Random();
		num = rd.nextInt(100) + 1;
		l1 = new JLabel("숫자를 추측하시오");
		l1.setBounds(80, 10, 150, 20);
		
		tf = new JTextField();
		tf.setBounds(190, 10, 150, 20);
		tf.addKeyListener(new KeyListener());
		tf.setFocusable(true);
		tf.requestFocus();
		
		l2 = new JLabel("=====");
		Font font = new Font("SamSerif", Font.BOLD, 50);	// 폰트
		l2.setFont(font);
		l2.setHorizontalAlignment(JLabel.CENTER);
		l2.setOpaque(true);		// 라벨의 색상을 바꿀 수 있도록 설정
		l2.setBackground(Color.WHITE);
		l2.setBounds(0, 45, 400, 50);
		
		b1 = new JButton("NEW");
		b2 = new JButton("END");
		b1.addActionListener(new ButtonListener());
		b2.addActionListener(new ButtonListener());
		b1.setBounds(115, 120, 80, 30);
		b2.setBounds(205, 120, 80, 30);
		
		add(l1); add(tf); add(l2); add(b1); add(b2);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	protected class ButtonListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() == b1) {
				l2.setText("=====");
				tf.setText("");
				l2.setBackground(Color.WHITE);
				num = rd.nextInt(100) + 1;
			} else {
				System.exit(0);		// 종료
			}
		}
	}
	protected class KeyListener extends KeyAdapter {
    	@Override
		public void keyPressed(KeyEvent kE) {
			int keycode = kE.getKeyCode();
			try {
				int userNum = Integer.parseInt(tf.getText());
				if (keycode == KeyEvent.VK_ENTER) {
					if (num > userNum) {
						l2.setText("UP");
						l2.setBackground(Color.PINK);
						tf.setText("");
					} else if (num < userNum) {
						l2.setText("DOWN");
						l2.setBackground(Color.CYAN);
						tf.setText("");
					} else {
						l2.setText("GREAT");
						l2.setBackground(Color.GREEN);
						tf.setText("");
					}
				}
			} catch(Exception E) {
				System.out.println(E.toString());
			}
		}
	}
	public static void main(String[] args) {
		new Q10();
	}

}
728x90