수다닷컴

  • 해외여행
    • 괌
    • 태국
    • 유럽
    • 일본
    • 필리핀
    • 미국
    • 중국
    • 기타여행
    • 싱가폴
  • 건강
    • 다이어트
    • 당뇨
    • 헬스
    • 건강음식
    • 건강기타
  • 컴퓨터
    • 프로그램 개발일반
    • C언어
    • 비주얼베이직
  • 결혼생활
    • 출산/육아
    • 결혼준비
    • 엄마이야기방
  • 일상생활
    • 면접
    • 취업
    • 진로선택
  • 교육
    • 교육일반
    • 아이교육
    • 토익
    • 해외연수
    • 영어
  • 취미생활
    • 음악
    • 자전거
    • 수영
    • 바이크
    • 축구
  • 기타
    • 강아지
    • 제주도여행
    • 국내여행
    • 기타일상
    • 애플
    • 휴대폰관련
  • 프로그램 개발일반
  • C언어
  • 비주얼베이직

자바 swing 버튼을 이용한 야구 문제 인데;; 잘 안되네요..ㅠ.ㅠ

알찬마루

2023.04.01

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Baseb extends JFrame implements ActionListener{
int count;
int key;
int strike, ball;
int[] usr= new int[3];
int[] com= new int[3];
boolean gameover= false;
JLabel display; //입력한 숫자 표시 레이블
JTextArea history; //볼카운트 기록 보여주는 텍스트 에어리어
JButton[] buttons= new JButton[12];
Container con;
JPanel p1,p3,p2;
JFrame fr;

public void go(){

buttons[0] = new JButton(7);
buttons[1] = new JButton(8);
buttons[2] = new JButton(9);
buttons[3] = new JButton(4);
buttons[4] = new JButton(5);
buttons[5] = new JButton(6);
buttons[6] = new JButton(1);
buttons[7] = new JButton(2);
buttons[8] = new JButton(3);
buttons[9] = new JButton(←);
buttons[10] = new JButton(다시입력);
buttons[11] = new JButton(입력완료);

fr = new JFrame();

con = fr.getContentPane();

p1 = new JPanel();
p2 = new JPanel();
p3 = new JPanel();

display = new JLabel();
history = new JTextArea(7,50);
display.setHorizontalAlignment(JLabel.RIGHT);

/*fr.getContentPane().add(BorderLayout.NORTH, p1);
fr.getContentPane().add(BorderLayout.CENTER, p2);
fr.getContentPane().add(BorderLayout.SOUTH, p3);
fr.setSize(600, 600);
fr.setVisible(true);
*/
con.add(p1,BorderLayout.NORTH);
con.add(p2,BorderLayout.CENTER);
con.add(p3,BorderLayout.SOUTH);

p2.setLayout (new GridLayout(4,4));

p1.add(display);

p2.add(buttons[0]);
p2.add(buttons[1]);
p2.add(buttons[2]);
p2.add(buttons[3]);
p2.add(buttons[4]);
p2.add(buttons[5]);
p2.add(buttons[6]);
p2.add(buttons[7]);
p2.add(buttons[8]);
p2.add(buttons[9]);
p2.add(buttons[10]);
p2.add(buttons[11]);

p3.add(history);

buttons[0].addActionListener(this);
buttons[1].addActionListener(this);
buttons[2].addActionListener(this);
buttons[3].addActionListener(this);
buttons[4].addActionListener(this);
buttons[5].addActionListener(this);
buttons[6].addActionListener(this);
buttons[7].addActionListener(this);
buttons[8].addActionListener(this);
buttons[9].addActionListener(this);
buttons[10].addActionListener(this);
buttons[11].addActionListener(this);

fr.setTitle(야구게임);
fr.setSize(600,600);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setVisible(true);

/*
do-while문을 이용하여 3개의 난수 구한 후 com 배열에 저장
*/
Random r= new Random();
com[0]= Math.abs(r.nextInt() % 9) + 1;

do{
com[1]= Math.abs(r.nextInt() % 9) + 1;
}while(com[1]==com[0]);
do{
com[2]= Math.abs(r.nextInt() % 9) + 1;
}while((com[2]==com[0])||(com[2]==com[1]));
System.out.println(com[0] +, + com[1] +, + com[2]);
/*
변수들 초기화
*/
count= 0;
key= 0;
usr[0]= usr[1]= usr[2]= 0;
}

public void actionPerformed(ActionEvent e){
display.setText(e.getActionCommand());

if(gameover) return;
/*
← 버튼 클릭 시 마지막으로 입력한 숫자부터 하나씩 감소(지우기)
*/
if(e.getSource()==buttons[0]){
if(key0){
key--;
display.setText();
for(int i=0; ikey; i++){
 sp; display.setText(display.getText() + usr[i]);
}
}
/*
다시입력 버튼 클릭 시 배열의 내용 모두 지우기
*/
}else if(e.getSource()==buttons[10]){
key= 0;
usr[0]= usr[1]= usr[2]= 0;
display.setText();
/*
입력완료 버튼 클릭 시 user 배열과 com 배열 비교하여 볼카운트 계산.
계산된 결과는 history 텍스트 에어리어에 출력.
strike 값이 3개 이거나 시도 횟수가 11이라면 시도 횟수에 따라
메세지 history 텍스트 에어리어에 출력.
그리고 종료.
strike 값이 3개가 아니고 시도 횟수도 11미만이라면
입력받은 user 배열을 지우고 플레이어가 다시 추측할 기회 제공.
*/
}else if(e.getSource()==buttons[11]){
if(key==3){
strike = ball = 0;

if(usr[0]==com[0]) strike++;
if(usr[1]==com[1]) strike++;
if(usr[2]==com[2]) strike++;
if(usr[0]==com[1]) ball++;
if(usr[0]==com[2]) ball++;
if(usr[1]==com[0]) ball++;
if(usr[1]==com[2]) ball++;
if(usr[2]==com[0]) ball++;
if(usr[2]==com[1]) ball++;

history.append(usr[0] +, + usr[1] +, + usr[2] +
- Strike: + strike + Ball: + ball +\n);
count++;
key= 0;
usr[0]= usr[1]= usr[2]= 0;
display.setText();
if((strike==3)||(count==11)){
if(count=2){
history.append(\n평가: 참 잘했어요!);
}else if(count=5){
history.append(\n평가: 잘했어요!);
}else if(count=9){
history.append(\n평가: 보통이네요!);
}else{
history.append(\n평가: 분발하세요!);
}
gameover= true;
display.setText( Game Over ! );
history.append(\n\n게임 끝);
}
}else{
// 숫자가 3개 미만을 누른 경우
}
}else{ // 숫자 입력
if(key3){
char butVal= ((Button)e.getSource()).getLabel().charAt(0);
usr[key] = Integer.valueOf(String.valueOf(butVal)).intValue();
boolean same= false;
switch(key){
case 2:
if(usr[key]==usr[1]) same= true;
case 1:
if(usr[key]==usr[0]) same= true;
}

if(same){
// 같은 숫자를 누른 경우
}else{
display.setText(display.getText() + butVal);
key++;
}
}else{
// 숫자를 3개 이상 누른 경우
}
}
}
public static void main(String[] args){
Baseb GJ = new Baseb();
GJ.go();
}
}인터페이스는 다 구축 했는데;; 실행 해서 버튼을 클릭하면 값이 입력 안되네요;;ㅠ.ㅠ 에러 뜨면서;;

역시 swing 은 너무 어려워요.ㅠ.ㅠ 팁좀 주세요..ㅠ

참고로 버튼은 3번까지 클릭 가능 하며 클릭한 버튼의 숫자는 라벨에 표시 되어야 하고

이걸 usr 라는 배열에 값을 하나씩 넣기만 하면 될텐데;; 아흑;;

그럼 조언 부탁 드립ㄴ다;;

신청하기





COMMENT

댓글을 입력해주세요. 비속어와 욕설은 삼가해주세요.

  • 채움늘

    일단 버튼이 하는 역할이 일단 역할이 잘못된 듯 하네여...예를 들면 button[0]은 을 의미를 하는데...감소 어쩌구 저쩌구....일단 한꺼번에 하시는 것보다 먼저 숫자를 입력하는것부터 그다음에 비교하는 이런식으로 하시면 될듯.....아~~ 제꺼 하다가 하도 머리가 아파서 주절이 떠들어 봤네여...

번호 제 목 글쓴이 날짜
2701123 간단한 select 질문입니다 (3) 천사의눈물 2025-07-11
2701061 비베질문.. 똘끼 2025-07-10
2701034 메일폼 내 script 삽입가능한 방법 없을까요.. (2) 마음새 2025-07-10
2701008 분명히 버튼을 만들었는데 액션이 안걸립니다. (3) 재찬 2025-07-10
2700923 전체중앙정렬&독타입&쿼크모드 ㅜㅠ (8) 푸른들 2025-07-09
2700893 질문드리겠습니다. 도도한 2025-07-09
2700793 무비클립에 마우스 오버시 랜덤으로 효과음 나기는 어떻게 ;; (1) 바닐라 2025-07-08
2700741 웹전송? (2) 연와인 2025-07-07
2700686 카테고리 호버시 세부카테고리 보이게하는 것, css로만 가능할까요?? (3) 다힘 2025-07-07
2700658 메타태그 질문드립니다..ㅠㅠ;;; 모해 2025-07-07
2700632 외부에서 이미지 파일을 불러와야 합니다. 도와주세요. (4) 에일린 2025-07-06
2700579 (air + as3) smtp 이용해서 첨부파일 포함해서 메일 보내기 물보라 2025-07-06
2700524 클릭시 밑에 메뉴 나오게 (4) 새솔 2025-07-05
2700505 activex를 비쥬얼6.0으로 만들었는데요 비스타 배포시에 안되서 질문드립니다 (3) 참이 2025-07-05
2700452 c언어에서... 자료형 구분.... (3) 시내 2025-07-05
2700422 버전에 관해 질문 라온제나 2025-07-04
2700393 mysql이 갑자기!!!!!!!!!!!!!!!에러가;; (2) 소미 2025-07-04
2700359 3.0 ) SimpleButton 상태 강제 변경 (3) 희선 2025-07-04
2700304 ie8 전용핵 문의 (3) 여자 2025-07-03
2700281 이런경우 어떻게 코딩해야 표준에 따르는건가요? (6) 늘솜 2025-07-03
<<  이전  1 2 3 4 5 6 7 8 9 10  다음  >>

수다닷컴 | 여러분과 함께하는 수다토크 커뮤니티 수다닷컴에 오신것을 환영합니다.
사업자등록번호 : 117-07-92748 상호 : 진달래여행사 대표자 : 명현재 서울시 강서구 방화동 890번지 푸르지오 107동 306호
copyright 2011 게시글 삭제 및 기타 문의 : clairacademy@naver.com