Eclipse Window Builder Monty hall gui

时间:2013-08-13 01:47:45

标签: java eclipse windowbuilder

我的程序设置为测试Monty Hall问题10000次,然后将文本框设置为轮数(10000)和获胜次数,只有它不取第二个文本框并在方法为时设置文本叫,谁能告诉我为什么?

 package com.main.www;

import java.awt.EventQueue;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class MontyHallRedo {
public static final Random gen = new Random();
public static final int ROUNDS = 10000;

/** chooses a random door other than door1 or door2 */
private static int chooseAnotherDoor(int door1, int door2) {
    int result;
    do
        result = gen.nextInt(3);
    while (result == door1 || result == door2);
    return result;
}

private JFrame frame;
private JTextField textField;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MontyHallRedo window = new MontyHallRedo();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    calculate();
}

String ROUNDS2 = String.valueOf(ROUNDS);

private JLabel lblRoundsWon;
private static JTextField textField_1;

/**
 * Create the application.
 */
public MontyHallRedo() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {

    calculate();

    frame = new JFrame();
    frame.setBounds(100, 100, 716, 507);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JLabel lblRounds = new JLabel("Rounds Played:");
    lblRounds.setBounds(10, 155, 98, 49);
    frame.getContentPane().add(lblRounds);

    textField = new JTextField();
    textField.setBounds(94, 169, 86, 20);
    frame.getContentPane().add(textField);
    textField.setColumns(10);
    textField.setText(ROUNDS2);
    textField.setEditable(false);

    lblRoundsWon = new JLabel("Rounds Won:");
    lblRoundsWon.setBounds(237, 155, 68, 49);
    frame.getContentPane().add(lblRoundsWon);

    textField_1 = new JTextField();
    textField_1.setBounds(315, 169, 86, 20);
    frame.getContentPane().add(textField_1);
    textField_1.setColumns(10);
    textField_1.setEditable(false);

}

private static void calculate() {
    int wins = 0;
    for (int i = 0; i < ROUNDS; i++) {
        int prize = gen.nextInt(3);
        int userChoice1 = gen.nextInt(3);
        // host opens door other than user's choice without prize
        int hostChoice = chooseAnotherDoor(prize, userChoice1);
        // user always switches
        int userChoice2 = chooseAnotherDoor(userChoice1, hostChoice);
        if (userChoice2 == prize)
            wins++;
        textField_1.setText(String.format("%.4f", wins));
    }
}
}

1 个答案:

答案 0 :(得分:0)

在创建GUI对象之前,calculate()会调用

initialize()

textField_1.setText(String.format("%.4f", wins));

当调用上面的行时,textField_1不是有效的对象。