私はJavaを学習するのにわずか6〜7週間しかないので、私のコードが怠けていたり、用語がオフであれば事前にお詫びします。私は乱数を作成し、正しい数を得るまでユーザーが推測できるプログラムを作成しようとしています。それは私のための学習経験以外の本当の目的を果たさない。Java - 数値ゲーム - 複数のActionListenerが同じクラスにあります
私は基本的なプログラムを動作させていますが、私はそれを改善し、経験を得るために他の要素を追加したいだけです。
プログラムはJFrameで実行され、ユーザーが推測を入力するためのJTextFieldがあります。 JTextFieldのActionListener設定があります。私は、ゲームの始めに表示されるスタートボタンを追加したいと思います。ユーザーが開始ボタンをクリックすると、JTextFieldがアクティブになります。また、ユーザーが正しい答えを推測すると、スタートボタンを使用してプログラムをリセットしたいと考えています。私はこれを成功させるためにいくつかの方法を実験しました。私はこれが同じクラスの複数のActionListenersを必要とすると考えています。私はこれが可能かどうかも分かりません。
ここに私のコードです。助けを前にありがとう。
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);
}
}
プログラムに「再起動」オプションを実装する方法はいくつかあります。どの部分に問題があるのか正確に説明できますか? –