2013-12-09 3 views
0

Я работаю над java-игрой для класса, где мы реализуем игру nim. Я думал, что приближаюсь к завершению, но когда я запускал программу, ничего не появляется. Он просто говорит, что сборка выполнена успешно и завершается. Я никогда не увижу игру или не сыграю ее. Ниже приведен мой код для приложения.Нет визуального отображения

package Nim; 

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

public class Nim extends JFrame implements ActionListener { 

    // Number of stickSpace that is needed for the sticks; 
    int rowspace = 3; 

    // Buttons for the human to click to take turns playing witht the computer. 
    private JButton humanMove, 
        computerMove; 

    // whatRow = what row the user would like to remove from 
    // howMany = how many sticks to take from each row 
    private JComboBox whatRow, 
         howMany; 

    // Creates an array of JTextFields with the rowspace as a size. 
    private JTextField[] stickSpace = new JTextField[rowspace]; 

    // Creates the game; 
    private Nimgame nimgame; 

    public void Nim(){ 

     //As requireed, we use a loop to fill the array. 
     for(int i=0; i<rowspace ;i++){ 
      stickSpace[i] = new JTextField(5); 
     } 


     // Creates pulldown menus for the user to select the whatRow s/he 
     // wants to choose from, and another for howMany s/he wants to take. 
     whatRow = new JComboBox(); 
     howMany = new JComboBox(); 

     // Add the options to the pulldown menus so the player can choose. 
     // 0-2 because the array index starts at 0. 1-3 for the amount of sticks. 

     for(int p=0; p<=3; p++){ 
      if(p<3){ 
       whatRow.addItem(p); 
      } 
      if(p>0){ 
       howMany.addItem(p); 
      } 
     } 

     // Adds the text "Human Turn" and "CPU Turn" to the buttons used for turns. 
     humanMove = new JButton("Human Turn"); 
     computerMove = new JButton("CPU Turn"); 

     // Adds a listener to the buttons to signal the game its time to act. 
     humanMove.addActionListener(this); 
     computerMove.addActionListener(this); 

     // Creates a gridlayout (3,2) with 3 rows and two columns. 
     JPanel gridpanel = new JPanel(new GridLayout(3,2)); 

     // Labels the rows so the player knows it starts at row Zero - Three. 
     gridpanel.add(new JLabel("Row Zero", JLabel.LEFT)); 
     gridpanel.add(stickSpace[0]); 
     gridpanel.add(new JLabel("Row One", JLabel.LEFT));   
     gridpanel.add(stickSpace[1]); 
     gridpanel.add(new JLabel("Row Two", JLabel.LEFT));   
     gridpanel.add(stickSpace[2]); 

     // Creates another gridlayout this time with 4 rows and 2 columns. 
     // This sill be used to add the comboboxes, labels, and buttons. 
     JPanel mainPanel = new JPanel(new GridLayout(4,2)); 
     mainPanel.add(new JLabel("Remove from Row:", JLabel.RIGHT)); 
     mainPanel.add(whatRow); 
     mainPanel.add(new JLabel("# To Remove:", JLabel.RIGHT)); 
     mainPanel.add(howMany); 
     mainPanel.add(humanMove); 
     mainPanel.add(computerMove); 

     // This adds the gridpanel and the main panel to the visual 
     // application, but they are still not visiable at this moment. 
     getContentPane().add(gridpanel, BorderLayout.NORTH); 
     getContentPane().add(mainPanel, BorderLayout.SOUTH); 

     // This sections sets the title, size, position on screen, sets it visiable, 
     // sets the background color, and makes it exit on close of the visual application. 
     setTitle("The Game of Nim"); 
     setSize(300, 250); 
     setBackground(Color.yellow); 
     setVisible(true); 

     // Creates the actual game to play. 
     nimgame = new Nimgame(); 

     // Prints out the sticks in each row. 
     for(int p=0; p<3; p++){ 
      stickSpace[p].setText(nimgame.addSticks(p)); 
     } 
    } 

    // Method to handle when an action lister find an action event 
    public void actionPerformed(ActionEvent e){ 

     // Checks if the humanMove button has been pressed 
     if(e.getSource() == humanMove){ 
      int foo = whatRow.getSelectedIndex(); 
      int bar = howMany.getSelectedIndex()+1; 
      nimgame.stickRemove(foo, bar); 

      for(int p=0; p<3; p++){ 
       stickSpace[p].setText(nimgame.addSticks(p)); 
      }    
     } 

     // Checks if the computerMove button has been pressed. 
     if(e.getSource() == computerMove){ 
      nimgame.computerRandom(); 
      for(int p=0; p<3; p++){ 
       stickSpace[p].setText(nimgame.addSticks(p)); 
      }    
     } 

     // Checks to see if the game is over or not. 
     if(nimgame.isDone()){ 
      JOptionPane.showMessageDialog(null, "Game Over Player Player" + nimgame.whoWon()); 
     } 
    } 

    public static void main(String[] args) { 

     Nim NIM = new Nim(); 
    } 
} 

Любая идея, почему бы ничего не появилось? Я решил, что забыл установить Видимость, но это было не так. Любая помощь приветствуется.

ответ

2
public void Nim(){ 

Это не конструктор, это void объявление метода с очень запутанным именем. Как вы не объявить конструктор вообще, у вас есть неявный конструктор по умолчанию, который называется здесь:

Nim NIM = new Nim(); 

но конструктор по умолчанию не делать то, что вы ожидали бы, так что вы ничего не видите , Чтобы это исправить, изменить вышеупомянутое определение метода для определения конструктора путем удаления void:

public Nim() { 
+1

Большое спасибо kviiri ... Я смотрел на это в течение часа, и это сводило меня с ума! Думаю, иногда вам просто нужна дополнительная пара глаз! Это позволило решить проблему и будет отмечен ответ, когда я смогу. Еще раз спасибо, и у вас хороший день! – NerdsRaisedHand

+0

@NerdsRaisedHand, это очень распространено. Рад помочь! – kviiri

Смежные вопросы