当我尝试运行它时,为什么我的程序会冻结/崩溃?

时间:2015-09-23 13:43:07

标签: java netbeans dice

这不是一个完整的程序,但我想知道为什么当我按下“JButton”时它会冻结。我目前正在制作一个骰子游戏,到目前为止一切正常,但我不明白为什么它不会在此刻运行。感谢您事先的帮助:)

PS。在方法diceLogic中添加while循环后,问题就开始了。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dicegame_leonardasp;

/**
 *
 * @author LeoAsp
 */
import java.awt.Dimension;
import java.awt.Image;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.util.Random;
import javafx.scene.control.Cell;

public class DiceGameGui extends javax.swing.JFrame {

  //Instansvariabel
  //Skapa instans av Randomklassen
  Random rand = new Random();

  public DiceGameGui() {
    initComponents();

  }

  public String doMessage() {
    String message = "";

    return message;
  }

  public String doReDice() {
    String image = "";

    int randNum = rand.nextInt(6 - 1) + 1;

    if (randNum == 1) {
      image = "one.gif";
    } else if (randNum == 2) {
      image = "two.gif";
    } else if (randNum == 3) {
      image = "three.gif";
    } else if (randNum == 4) {
      image = "four.gif";
    } else if (randNum == 5) {
      image = "five.gif";
    } else if (randNum == 6) {
      image = "six.gif";
    } else {
      dispose();
    }
    return image;
  }

  public void diceLogic(int players, int dice) {

    jDiceResult.removeAll();
    jDiceResult.setLayout(new java.awt.GridLayout(6, 5));
    JLabel playersArray[][] = new JLabel[players][dice];
    int j;
    int i;
    for (i = 0; i <= players; i++) {

      for (j = 0; j < dice; j++) {

        playersArray[i][j] = new JLabel();

        playersArray[i][j].setIcon(new ImageIcon(doReDice()));
        playersArray[i][j].setPreferredSize(new Dimension(60, 50));

        //  playersArray[i][j].setPreferredSize(new Dimension(20, 20));
        //playersArray[i][j].setMinimumSize(new Dimension(20, 20));
        //playersArray[i][j].setMaximumSize(new Dimension(20, 20));
        jDiceResult.add(playersArray[i][j]);
        jDiceResult.revalidate();
        jDiceResult.repaint();

      }

      while (j <= 6) {
        jDiceResult.add(javax.swing.Box.createGlue());
      }

    }

  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @
  SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  private void initComponents() {

      jLabel1 = new javax.swing.JLabel();
      jLabel2 = new javax.swing.JLabel();
      jLabel3 = new javax.swing.JLabel();
      jBoxPlayers = new javax.swing.JComboBox();
      jBoxDice = new javax.swing.JComboBox();
      jBtnRoll = new javax.swing.JButton();
      jScrollPane1 = new javax.swing.JScrollPane();
      jTextArea1 = new javax.swing.JTextArea();
      jButton1 = new javax.swing.JButton();
      jDiceResult = new javax.swing.JPanel();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

      jLabel1.setFont(new java.awt.Font("Menlo", 0, 18)); // NOI18N
      jLabel1.setText("Players:");

      jLabel2.setFont(new java.awt.Font("Menlo", 0, 18)); // NOI18N
      jLabel2.setText("Dice:");

      jLabel3.setFont(new java.awt.Font("Menlo", 0, 18)); // NOI18N

      jBoxPlayers.setFont(new java.awt.Font("Menlo", 1, 14)); // NOI18N
      jBoxPlayers.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
        "1", "2", "3", "4", "5"
      }));
      jBoxPlayers.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
          jBoxPlayersActionPerformed(evt);
        }
      });

      jBoxDice.setFont(new java.awt.Font("Menlo", 1, 14)); // NOI18N
      jBoxDice.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
        "1", "2", "3", "4", "5", "6"
      }));
      jBoxDice.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
          jBoxDiceActionPerformed(evt);
        }
      });

      jBtnRoll.setFont(new java.awt.Font("Menlo", 0, 18)); // NOI18N
      jBtnRoll.setText("Roll the Dice");
      jBtnRoll.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
          jBtnRollActionPerformed(evt);
        }
      });

      jTextArea1.setEditable(false);
      jTextArea1.setColumns(20);
      jTextArea1.setRows(5);
      jScrollPane1.setViewportView(jTextArea1);

      jButton1.setFont(new java.awt.Font("Menlo", 0, 14)); // NOI18N
      jButton1.setText("Show Highscore");

      jDiceResult.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
      jDiceResult.setPreferredSize(new java.awt.Dimension(250, 300));

      javax.swing.GroupLayout jDiceResultLayout = new javax.swing.GroupLayout(jDiceResult);
      jDiceResult.setLayout(jDiceResultLayout);
      jDiceResultLayout.setHorizontalGroup(
        jDiceResultLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 246, Short.MAX_VALUE)
      );
      jDiceResultLayout.setVerticalGroup(
        jDiceResultLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 296, Short.MAX_VALUE)
      );

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
          .addContainerGap()
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
              .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jBoxPlayers, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                  .addGap(91, 91, 91)
                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                      .addComponent(jLabel2)
                      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                      .addComponent(jLabel3))
                    .addComponent(jBoxDice, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGap(18, 18, 18)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jBtnRoll, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jDiceResult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
          .addContainerGap())
      );
      layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
          .addContainerGap()
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(jLabel2)
                .addComponent(jLabel3))
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jBoxPlayers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jBoxDice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addComponent(jBtnRoll, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jDiceResult, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
          .addComponent(jButton1)
          .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      );

      pack();
    } // </editor-fold>                        

  private void jBoxPlayersActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
  }

  private void jBoxDiceActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
  }

  private void jBtnRollActionPerformed(java.awt.event.ActionEvent evt) {
    int dice = Integer.parseInt(jBoxDice.getSelectedItem().toString());
    int players = Integer.parseInt(jBoxPlayers.getSelectedItem().toString());

    diceLogic(players, dice);

  }

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {

    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info: javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(DiceGameGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(DiceGameGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(DiceGameGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(DiceGameGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        new DiceGameGui().setVisible(true);
      }
    });
  }

  // Variables declaration - do not modify                     
  private javax.swing.JComboBox jBoxDice;
  private javax.swing.JComboBox jBoxPlayers;
  private javax.swing.JButton jBtnRoll;
  private javax.swing.JButton jButton1;
  private javax.swing.JPanel jDiceResult;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JTextArea jTextArea1;
  // End of variables declaration                   
}

2 个答案:

答案 0 :(得分:3)

这是问题所在:

while (j <= 6) {
    jDiceResult.add(javax.swing.Box.createGlue());
}

使用此行,您可以创建一个无限循环,因为您检查j<=6是否但不更改j的值,因此j<=6始终为true
我想您要将while更改为if

答案 1 :(得分:0)

我想:

while (j <= 6) {
    jDiceResult.add(javax.swing.Box.createGlue());
}

我想可能应该是:

if (j <= 6) {
    jDiceResult.add(javax.swing.Box.createGlue());
}