我只有6 - 7周的時間學習Java,所以如果我的代碼是草率或術語關閉,我會事先致歉。我試圖創建一個程序來創建一個隨機數,並允許用戶猜測,直到他們得到正確的數字。除了爲我學習的經驗之外,它沒有真正的目的。Java - 數字遊戲 - 同一類中的多個ActionListener
我有基本的程序工作,我只是想添加其他元素來改善它,並獲得經驗。
該程序在JFrame中運行,並具有供用戶輸入其猜測的JTextField。我爲JTextField設置了ActionListener。我想添加一個在遊戲開始時顯示的開始按鈕。當用戶單擊開始按鈕時,JTextField應該變爲活動狀態。另外,當用戶點擊猜測正確答案時,我想使用開始按鈕來重置程序。我已經嘗試了幾種方法來做到這一點,但沒有成功。我相信這將需要同一個類中的多個ActionListener。我甚至不確定這是否可能?
這是我的代碼。預先感謝您的幫助。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class JMyFrame2 extends JFrame implements ActionListener {
Random num = new Random();
int computerGenerated = num.nextInt(1000);
public int userSelection;
JTextField numberField = new JTextField(10);
JLabel label1 = new JLabel();
Container con = getContentPane();
int previousGuess;
// constructor for JMyFrame
public JMyFrame2(String title) {
super(title);
setSize(750, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label1 = new JLabel(
"I have a number between 1 and 1000 can you guess my number?" + "Please enter a number for your first guess and then hit Enter.");
setLayout(new FlowLayout());
add(numberField);
add(label1);
System.out.println(computerGenerated);
numberField.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
userSelection = Integer.parseInt(numberField.getText());
con.setBackground(Color.red);
if (userSelection == computerGenerated) {
label1.setText("You are correct");
con.setBackground(Color.GREEN);
} else if (userSelection > computerGenerated) {
label1.setText("You are too high");
} else if (userSelection < computerGenerated) {
label1.setText("You are too low");
}
}
}
public class JavaProgram5 {
public static void main(String[] args) {
JMyFrame2 frame2 = new JMyFrame2("Assignment 5 - Number Guessing Game");
frame2.setVisible(true);
}
}
在程序中實現「重啓」選項有幾種不同的方法。你能解釋一下你在哪一部分遇到麻煩嗎? –