정리노트

[자바/java] Swing 연습문제 가위바위보 본문

프로그래밍/Java

[자바/java] Swing 연습문제 가위바위보

Rolen 2023. 1. 17. 20:40

사용 이벤트
mouseClicked
버튼 - ActionListener

버튼 객체배열 사용

가위바위보를 클릭할 때 마다 결과가 나타나고 컴퓨터의 결과는 색상으로 표시.
유저와 컴퓨터의 버튼 색상은 고정되었다가 새로 버튼을 클릭하면 바뀐다.

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

class Q11 extends JFrame {
	Random rd;
	JLabel title, vs, l1, l2, result;
	JButton uB[];
	JButton cB[];
	String bT[] = {"가위", "바위", "보"};
	Q11() {
		setTitle("가위바위보");
		setSize(500, 300);
		setLayout(null);
		Font font = new Font("SamSerif", Font.BOLD, 20);
		
		title = new JLabel("가위, 바위, 보");
		title.setFont(font);
		title.setBounds(0, 10, 480, 20); add(title);
		title.setHorizontalAlignment(JLabel.CENTER);
		vs = new JLabel("VS");
		vs.setFont(font);
		vs.setBounds(230, 120, 40, 20);	add(vs);
		uB = new JButton[3];
		cB = new JButton[3];
		for (int i = 0; i < 3; i++) {
			uB[i] = new JButton(bT[i]); uB[i].setBounds(10, 40 + 40 * i +10+(i*10), 100, 40); add(uB[i]);
			cB[i] = new JButton(bT[i]);	cB[i].setBounds(373, 40 + 40 * i +10+(i*10), 100, 40); add(cB[i]);
			uB[i].addActionListener(new MyListener());
			uB[i].addMouseListener(new MouseListener());
			uB[i].setBackground(Color.WHITE);
			cB[i].setBackground(Color.WHITE);
		}
		l1 = new JLabel("USER"); l1.setBounds(44, 200, 50, 20); add(l1);
		l2 = new JLabel("COM"); l2.setBounds(410, 200, 50, 20); add(l2);
		
		result = new JLabel(""); 
		result.setFont(font);
		result.setBounds(0, 150, 484, 20);
		result.setHorizontalAlignment(JLabel.CENTER); add(result);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	protected class MyListener implements ActionListener {
    	@Override
		public void actionPerformed(ActionEvent e) {
			int user = 0; int com;
			rd = new Random();
			com = rd.nextInt(3);
			for (int i = 0; i < 3; i++) {
				if (e.getSource() == cB[i]) {
					user = i;
				}
				cB[i].setBackground(Color.WHITE);	// 버튼 색상 초기화
				uB[i].setBackground(Color.WHITE);
			}
			if (user == com) {
				result.setText("DRAW");
				cB[com].setBackground(Color.CYAN);	// 결과 후 색상변경 고정
			} else if (user == (com+1)%3) {
				result.setText("WIN");
				cB[com].setBackground(Color.CYAN);
			} else {
				result.setText("LOSE");
				cB[com].setBackground(Color.CYAN);
			}
		}
	}
	protected class MouseListener extends MouseAdapter {
    	@Override
		public void mouseClicked(MouseEvent mE) {
			JButton mB = (JButton) mE.getSource();
			mB.setBackground(Color.PINK);	// 결과 후 색상변경 고정
		}
	}
	public static void main(String[] args) {
		new Q11();
	}

}

728x90