Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- 저장소
- join()
- synchronized
- AssertJ
- 메소드
- SpringBoot
- Java
- 클래스
- GIT
- 프로그래머스스쿨
- Python
- SSL
- event
- 스프링부트
- docker
- StringBuilder
- JavaScript
- c#
- Dict
- class
- 자바
- array
- 객체
- 자바스크립트
- 배열
- Docker Desktop
- Swing
- thread
- JS
- 파이썬
Archives
- Today
- Total
정리노트
[자바/java] Swing 연습문제 숫자(UP/DOWN) 게임 본문
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
'프로그래밍 > Java' 카테고리의 다른 글
[자바/java] Swing 주소록 만들기 (1) | 2023.01.18 |
---|---|
[자바/java] Swing 연습문제 가위바위보 (1) | 2023.01.17 |
[자바/java] String클래스의 메소드 (0) | 2022.12.29 |
[자바/java] 인터페이스 (0) | 2022.12.28 |
[자바/java] 물체의 운동에너지 계산(제곱, printf) (0) | 2022.11.09 |