我只有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);
}
}
在程序中实现“重启”选项有几种不同的方法。你能解释一下你在哪一部分遇到麻烦吗? –