티스토리 뷰

카테고리 없음

GUI 연습하기_1

onaeonae1 2019. 5. 5. 15:15

3 x 10 짜리 버튼 배열을 만들어서 추가하고, 홀수 번 버튼과 짝수 번 버튼이 눌렀을 때 다르게 작동하도록 만들기.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PRAC3 extends JFrame implements ActionListener{
	JPanel P1 = new JPanel(); //홀짝 체크용 버튼 
	JPanel P2 = new JPanel(); //3x10 버튼들 올리는 용
	JButton[][] B = new JButton[3][10]; //2차원 버튼 배열 만들기
	JButton evenB = new JButton(); JButton oddB = new JButton();
	int evenValue = 0; int oddValue = 0 ;
	public PRAC3() {
		//PRAC3 기본 설정
		this.setLayout(new GridLayout(0,1));
		this.setSize(1400,300);
		
		//P1 설정
		P1.setLayout(new GridLayout());
		evenB.setText("0"); oddB.setText("0");
		evenB.setBackground(Color.cyan); oddB.setBackground(Color.GRAY);
		P1.add(evenB); P1.add(oddB);
		this.add(P1);
		
		//P2 설정 
		P2.setLayout(new GridLayout(0,10));
		for(int i=0; i<3; i++) {
			for(int j=0; j<10; j++) {
				int value = 10*i + j;
				B[i][j] = new JButton("버튼"+value);
				B[i][j].addActionListener(this); //ActionListener 추가
				B[i][j].setBackground(Color.white);
				P2.add(B[i][j]);
			}
		}
		this.add(P2);
		
		this.setVisible(true);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		for(int i=0; i<3; i++) {
			for(int j=0; j<10; j++) {
				int value = 10 * i + j ;
				if(e.getSource().equals(B[i][j])){
					//홀짝 구분하여 다른 효과 내기
					if(value%2==0) {
						B[i][j].setBackground(Color.GREEN);
						//짝수 버튼 건드려줌.
						evenValue++;
						evenB.setText(""+evenValue);
						//버튼 누른 것 표시
						JOptionPane.showMessageDialog(this, value+"번 버튼 눌렀음(짝수)");
						if(i>0) {
							B[i-1][j].setBackground(Color.GREEN);
						}
						if(i<2) {
							B[i+1][j].setBackground(Color.GREEN);
						}
						if(j>0) {
							B[i][j-1].setBackground(Color.GREEN);
						}
						if(j<9) {
							B[i][j+1].setBackground(Color.GREEN);
						}
					}
					else if(value%2==1) {
						B[i][j].setBackground(Color.DARK_GRAY);
						//홀수 버튼 건드려줌
						oddValue++;
						oddB.setText(""+oddValue);
						//버튼 누른 것 표시
						JOptionPane.showMessageDialog(this, value+"번 버튼 눌렀음(홀수)");
						if(i>0) {
							B[i-1][j].setBackground(Color.DARK_GRAY);
						}
						if(i<2) {
							B[i+1][j].setBackground(Color.DARK_GRAY);
						}
						if(j>0) {
							B[i][j-1].setBackground(Color.DARK_GRAY);
						}
						if(j<9) {
							B[i][j+1].setBackground(Color.DARK_GRAY);
						}
					}
				}
			}
		}
	}
	public static void main(String[] args) {
		new PRAC3();
	}
}

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
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 31
글 보관함