mojo's Blog

명품 JAVA Programming 제 10장 Open Challenge 본문

Java

명품 JAVA Programming 제 10장 Open Challenge

_mojo_ 2021. 7. 28. 01:20

Swing으로 간단한 갬블링 게임 만들기 code

import javax.swing.*; // JFrame
import java.awt.*; // Container
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.*;

public class MyFrame extends JFrame {
	
	private JLabel la[], result_La;
	
	public MyFrame() {
		setTitle("Open Challenge 10");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container c = getContentPane();
		
		c.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
		
		la=new JLabel[3];
		
		for(int i=0;i<la.length;i++) {
			la[i]=new JLabel(Integer.toString(0));
			la[i].setOpaque(true);
			la[i].setBackground(Color.PINK);
			la[i].setForeground(Color.YELLOW);
			la[i].setSize(100,100);
			c.add(la[i]);
		}
		
		result_La=new JLabel("시작합니다.");
		result_La.setSize(100,100);
		c.add(result_La);
		
		c.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				char keyChar=e.getKeyChar();
				if(keyChar=='\n') {
					int op=1, before=-1;
					for(int i=0;i<3;i++) {
						int r=(int)(Math.random()*4+1);
						la[i].setText(Integer.toString(r));
						if(before==r) {
							op++;
						}
						before=r;
					}
					if(op==3) result_La.setText("축하합니다!!!");
					else result_La.setText("아쉽군요");
				}
			}
		});
		
		setSize(300, 150); // 프레임 크기 300x300
		setVisible(true); // 프레임 출력
		
		c.setFocusable(true);
		c.requestFocus();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new MyFrame();
	}

}

'Java' 카테고리의 다른 글

JCheckBox / JRadioButton 연습하기  (0) 2021.07.28
명품 JAVA Programming 제 10장 실습문제 5번  (0) 2021.07.28
KeyListener / MouseListener  (0) 2021.07.28
Adapter Class  (0) 2021.07.28
Action Listener 작성하기  (0) 2021.07.28
Comments