我正在尝试将基于终端的猜谜游戏变成基于GUI的游戏。我的问题是,当我将所有代码放入main方法时总会出现问题。
我想我最后会编写main方法,它唯一的工作就是让GUI可见,但是我无法对非静态JFrame变量frame
进行静态引用。我是Java和编程的新手,我现在只是处于亏损状态。
代码
public class GuiGuess extends JPanel implements ActionListener{
JTextField guessField = new JTextField("Your Guess");
JTextField minField = new JTextField ("Minimum Boundary");
JTextField maxField = new JTextField ("Maximum Boundary");
JTextArea outputArea;
JButton checkButton;
JFrame frame = new JFrame("Guessing Game");
public GuiGuess(){
JFrame frame = new JFrame("Guessing Game");
JPanel textHolder = new JPanel();
JPanel buttonHolder = new JPanel();
textHolder.add(minField);
textHolder.add(maxField);
textHolder.add(guessField);
textHolder.add(outputArea);
buttonHolder.add(checkButton);
frame.getContentPane().add(textHolder, "North");
frame.getContentPane().add(buttonHolder, "South");
frame.setVisible(true);
checkButton.addActionListener(this);
}
int numGuesses = 0;
int counter = 0;
int guess = Integer.parseInt(guessField.getText());
public void actionPerformed(ActionEvent e){
if (counter < 1){
int min = Integer.parseInt(minField.getText());
int max = Integer.parseInt(maxField.getText());
int numToGuess = min + (int)(Math.random()*max);
}
guess = Integer.parseInt(guessField.getText());
numGuesses++;
counter++;
if (guess < numToGuess){
outputArea.setText("Your guess is too low");
}
else if (guess > numToGuess){
outputArea.setText("Your guess is too high");
}
else if (guess == numToGuess){
outputArea.setText("You Win! It took you "+numGuesses +"Tries!");
}
}
public static void main(String Args[]){
frame.setVisible(true);
}
}
答案 0 :(得分:1)
错误选项:将frame
设为静态。
更好:在GuiGuess
中创建方法:
public void show() {
frame.setVisible(true);
}
和您的main
:
GuiGuess gGuess = new GuiGuess();
gGuess.show();
因为frame
是类GuiGuess
的成员变量,因此更改它的状态应该通过GuiGuess
。
答案 1 :(得分:0)
Frame是GuiGuess类的成员....所以你需要使用instace
在static main中执行以下操作:
public static void main(String Args[]){
GuiGuess myGui = new GuiGuess( );
myGui.setVisible(true);
}