728x90
반응형
package Ex01;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NumClickGame extends JFrame{
private JLabel [] gameLabel = new JLabel[10]; //0~9까지
private int nextPressed = 0;
public NumClickGame() {
setTitle("Ten 레이블 클릭");
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(null);
setVisible(true);
for(int i=0; i<gameLabel.length; i++) {
gameLabel[i] = new JLabel(Integer.toString(i));
gameLabel[i].setFont(new Font("Gothic", Font.PLAIN, 15));
gameLabel[i].setForeground(Color.MAGENTA);
c.add(gameLabel[i]);
//0,1,2 순으로 삽입하면 2,1,0 순으로 화면에 출력됨
//그렇기 때문에 만약 2와 1이 같은 위치에 겹치게 되더라도 순서대로 클릭할 수 있다.
gameLabel[i].addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
JLabel la = (JLabel)e.getSource();
if(Integer.parseInt(la.getText()) == nextPressed) { //누른 숫자가 nextPressed라면
nextPressed++;
if(nextPressed == 10) {
nextPressed = 0;
configure(); //숫자를 다시 뿌림
}else {
la.setVisible(false);
}
}
}
});
}
configure(); //레이블 무작위 배치
}
private void configure() {
Container c = getContentPane();
for(int i=0; i<gameLabel.length; i++) {
gameLabel[i].setSize(15,15);
int xBound = c.getWidth() - gameLabel[i].getWidth();
int yBound = c.getHeight() - gameLabel[i].getHeight();
int x = (int)(Math.random()*xBound);
int y = (int)(Math.random()*yBound);
gameLabel[i].setLocation(x, y);
gameLabel[i].setVisible(true);
}
}
public static void main(String[] args) {
new NumClickGame();
}
}
0부터 순서대로 클릭하고 전부 클릭하면 다시 숫자가 뿌려짐
728x90
반응형
'JAVA > 예제' 카테고리의 다른 글
[JAVA/API] JAVA에서 공공 API 요청 및 출력하기 (0) | 2023.01.01 |
---|---|
[JAVA] 자판기 (0) | 2022.10.28 |
[JAVA] Graphics 미니그림판 (0) | 2022.10.28 |
[JAVA] Graphics 웃는 얼굴 (0) | 2022.10.28 |
[JAVA] 신호등 (0) | 2022.10.28 |
댓글