gpt4 book ai didi

Java - 数字游戏 - 同一个类中的多个 ActionListener

转载 作者:搜寻专家 更新时间:2023-10-31 19:32:31 24 4
gpt4 key购买 nike

我学习 Java 的时间只有 6 到 7 周,所以如果我的代码草率或术语不当,我提前道歉。我正在尝试创建一个程序来创建一个随机数并允许用户猜测直到他们得到正确的数字。除了对我的学习经验外,它没有任何实际用途。

我有基本的程序,我只是想添加其他元素来改进它并获得经验。

该程序在 JFrame 中运行,并有一个 JTextField 供用户输入他们的猜测。我为 JTextField 设置了 ActionListener。我想添加一个在游戏开始时显示的开始按钮。当用户单击开始按钮时,JTextField 应该变为 Activity 状态。另外,当用户点击猜测正确答案时,我想使用开始按钮来重置程序。我已经尝试了几种方法来做到这一点,但都没有成功。我相信这将需要同一个类中的多个 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);
}
}

最佳答案

当然你可以有多个 Action 监听器。事实上,您的类不应该实现它。

首先删除 actionPerformed 方法,并替换这一行:

    numberField.addActionListener(this);

有了这个:

    numberField.addActionListener(new ActionListener() {
@Override
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");
}
}
});

你可以在你打算添加的开始按钮上添加另一个 Action 监听器,遵循这种模式,使用匿名类。(它不一定是匿名类,这只是简单的演示。)

关于Java - 数字游戏 - 同一个类中的多个 ActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32798055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com