2012-04-19 5 views
2

"다시 재생"JButton으로 버튼을 재설정하려고합니다.스윙 버튼으로 응용 프로그램 재설정

import java.awt.*; 
import javax.swing.*; 
import java.awt.event.*; 
import java.awt.Toolkit; 
import java.awt.Image; 

public class HW4_TicTacToePanel extends JFrame implements ActionListener { 

// declare variables and arrays 
    private int counter = 0; 
    private String letter; 
    private boolean win = false; 
    private int[][] winConditions = new int[][]{ 
     {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //Horizontal wins 
     {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //Vertical wins 
     {0, 4, 8}, {2, 4, 6} //Diagonal wins 
    }; 
    // JFrame Instructions 
    // private JButton buttons[] = new JButton[12]; 
    // private JFrame gamewindow = new JFrame("Tic Tac Toe"); 
    // End JFrame 
    // Panel demo 
    private JPanel southPanel; //panel for replay and exit button 
    private JButton[] optButtons;//Exit and replay buttons 
    private JPanel centerPanel; 
    private JButton[] gameButtons;//Tic tac toe squares 
    private GridLayout myGridLayout; 

    // End panel demo 
    public HW4_TicTacToePanel() //Constructor 
    { 
     super("Tic Tac Toe"); //super calls the JFrame controller 
     southPanel = new JPanel();// instantiate panel 
     optButtons = new JButton[2];//create an array of 2 buttons 
     String[] buttonNames = {"Play Again", "Exit"}; 

     centerPanel = new JPanel(); //instantiate panel 
     gameButtons = new JButton[9];//creates an array of 9 buttons 
     myGridLayout = new GridLayout(3, 3, 2, 2); 

     setLayout(new BorderLayout());//set layout for JPanel 
     centerPanel.setLayout(myGridLayout);//set Layout for center panel 

     // add buttons to the centerPanel and add the ActionListener 
     for (int i = 0; i < gameButtons.length; i++) { 
      gameButtons[i] = new JButton(); 
      centerPanel.add(gameButtons[i]); 
      gameButtons[i].addActionListener(this); 
     } 

     add(centerPanel, BorderLayout.CENTER); //add panel to JFrame 

     // add buttons to the southPanel and add the ActionListener 
     for (int i = 0; i < optButtons.length; i++) { 
      optButtons[i] = new JButton(buttonNames[i]); 
      southPanel.add(optButtons[i]); 
     } 

     //add functionality to replay and exit buttons 
     optButtons[0].addActionListener(this); 
     optButtons[1].addActionListener(this); 

     add(southPanel, BorderLayout.SOUTH); //adds panel to JFrame 
    } 

    public void actionPerformed(ActionEvent a) { 
     // Add Image icons 
     counter++; 

     //Calculate whose turn it is by using modulus to determine even or odd 
    if (counter % 2 == 0) { 
     letter = "O"; 
     Icon o = new ImageIcon(getClass().getResource("O.gif")); 
     //Capture and show player input then disable button so it may not be reselected 
     JButton pressedButton = (JButton) a.getSource(); 
     pressedButton.setIcon(o); 
     pressedButton.setText(letter); 
     pressedButton.setEnabled(false); 
    } else if (a.getSource() == optButtons[0]) 
    { 
     // 
     //play again Instructions 
     // 
     System.exit(0); 
    } else if (a.getSource() == optButtons[1]) 
    { 
     System.exit(0); 
    } else { 
     letter = "X"; 
     Icon x = new ImageIcon(getClass().getResource("X.gif")); 
     //Capture and show player input then disable button so it may not be reselected 
     JButton pressedButton = (JButton) a.getSource(); 
     pressedButton.setIcon(x); 
     pressedButton.setText(letter); 
     pressedButton.setEnabled(false); 
    } 

//determine who won 
     for (int i = 0; i <= 7; i++) { 
      if (gameButtons[winConditions[i][0]].getText().equals(gameButtons[winConditions[i][1]].getText()) 
        & gameButtons[winConditions[i][1]].getText().equals(gameButtons[winConditions[i][2]].getText()) 
        & gameButtons[winConditions[i][0]].getText() != "") { 
       win = true; 
      } 
     } 

//Show victor dialog 
     if (win == true) { 
      JOptionPane.showMessageDialog(null, letter + " wins the game!"); 
      //Remove once optButtons are operational... 
      System.exit(0); 
     } else if (counter == 9 && win == false) { 
      JOptionPane.showMessageDialog(null, "The game was a tie!"); 
      //Remove once optButtons are operational... 
      System.exit(0); 
     } 
    } 

    public static void main(String[] args) { 
     HW4_TicTacToePanel starter = new HW4_TicTacToePanel(); 
    } 
} 

다시 재생 버튼의 경우 카운터를 재설정하고 게임 버튼에 저장된 값을 무효로 할 생각이었습니다. 나는 플레이어가 else if 문으로 이동하는 것과 같은 루프에서 이것을 구현할 것입니다.

나는 잠시 동안 아무런 도움없이 조언을 해왔다. 감사합니다.

+0

게임 보드를 재설정하기 위해 마지막 문장 대신에 else 문장의 위치를 ​​이동해야했습니다. {[I] \t \t \t \t \t \t \t gameButtons 경우 (a.getSource()는 == optButtons [0]) {\t \t \t 찾는 (; I Daishi100

+0

재생 버튼은 어디에 있습니까? –

답변

1

많은 종료 버튼을 사용하여 종료 할 수 있습니다.

import java.awt.*; 
import javax.swing.*; 
import java.awt.event.*; 
import java.awt.Toolkit; 
import java.awt.Image; 

public class HW4_TicTacToePanel extends JFrame implements ActionListener { 
    private int counter = 0; 
    private int [] [] winConditions = new int [] [] { 
     {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, // Horizontal wins 
     {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, // Vertical wins 
     {0, 4, 8}, {2, 4, 6} // Diagonal wins 
    }; 
    private JButton [] gameButtons; 

    public HW4_TicTacToePanel() 
    { 
     super ("Tic Tac Toe"); 
     JPanel southPanel = new JPanel(); 
     JButton [] optButtons = new JButton [2]; 
     String [] buttonNames = {"Play Again", "Exit"}; 
     JPanel centerPanel = new JPanel(); 
     gameButtons = new JButton [9]; 
     GridLayout myGridLayout = new GridLayout (3, 3, 2, 2); 
     setLayout (new BorderLayout()); 
     centerPanel.setLayout (myGridLayout); 
     for (int i = 0; i < gameButtons.length; i++) { 
      gameButtons [i] = new JButton(); 
      centerPanel.add (gameButtons [i]); 
      gameButtons [i].addActionListener (this); 
     } 

     add (centerPanel, BorderLayout.CENTER); 
     for (int i = 0; i < optButtons.length; i++) { 
      optButtons [i] = new JButton (buttonNames [i]); 
      southPanel.add (optButtons [i]); 
      optButtons [i].addActionListener (this);    
     } 
     add (southPanel, BorderLayout.SOUTH); 
     setSize (300, 300); 
     setLocation (200, 200); 
     setVisible (true); 
    } 

    private static Icon [] icon = new ImageIcon [] { 
     new ImageIcon ("/home/stefan/some/images/mini.null.jpg"), 
     new ImageIcon ("/home/stefan/daten/some/images/x.gif")}; 
    private static String [] letter = new String [] {"x", "o"}; 

    public void actionPerformed (ActionEvent a) { 
     // Add Image icons 
     counter++; 
     boolean win = false; 
     String cmd = a.getActionCommand(); 
     if (cmd.equals ("Play Again")) 
     { 
      dispose(); 
      HW4_TicTacToePanel.main (null); 
     } 
     else if (cmd.equals ("Exit")) 
     { 
      dispose(); 
     } else { 
      // Calculate whose turn it is by using modulus to determine even or odd 
      JButton pressedButton = (JButton) a.getSource(); 
      pressedButton.setIcon (icon [counter%2]); 
      pressedButton.setText (letter[counter%2]); 
      pressedButton.setEnabled (false); 
     } 
     //determine who won 
     for (int i = 0; i <= 7; i++) { 
      if (gameButtons [winConditions [i] [0]].getText().equals (gameButtons [winConditions [i] [1]].getText()) 
      & gameButtons [winConditions [i] [1]].getText().equals (gameButtons [winConditions [i] [2]].getText()) 
      & gameButtons [winConditions [i] [0]].getText() != "") { 
       win = true; 
      } 
     } 
     //Show victor dialog 
     if (win == true) { 
      JOptionPane.showMessageDialog (null, letter[counter%2] + " wins the game!"); 
     } else if (counter == 9 && win == false) { 
      JOptionPane.showMessageDialog (null, "The game was a tie!"); 
     } 
    } 

    public static void main (String [] args) { 
     new HW4_TicTacToePanel(); 
    } 
} 

몇 가지 힌트 :

  • 당신이 코드로 작성했는지 코멘트 반복하지 마십시오 여기에 몇 가지 코드 개선이다.
  • 모든 Java 프로그래머가 알아야 할 사항 (생성자의 모양, 인스턴스화의 속성,
  • )
  • JPanels는 일반적으로 ctor에서만 사용됩니다. 다른 곳에서 접근 할 필요가
  • 당신이 (주에서 선발) 변수를 참조하지 않는 경우 -.. 참조를 사용하지 않는
  • 이 왜 루프에 addActionListener에 넣지 않았다
  • (a.getSource() == optButtons[0])를? optButtons [0]은 무엇입니까? a.getActionCommand().equals ("Play Again")을 대신 사용하면 코드 자체가 문서화됩니다.
  • 배열을 사용하는 것이 좋습니다. 더 나아가십시오!
  • setSize/... location/... visible - 어떻게 처리 할 수 ​​있습니까?
  • 즐기십시오. :)
관련 문제