Bre*_*ent 5 java swing actionlistener
我只有6到7周的时间学习Java,所以如果我的代码很草率或术语关闭,我会提前道歉.我正在尝试创建一个创建随机数的程序,并允许用户猜测,直到他们得到正确的数字.除了学习经验之外,它没有任何实际意义.
我有基本程序工作,我只是想添加其他元素来改进它并获得经验.
该程序在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);
}
}
Run Code Online (Sandbox Code Playgroud)
当然,您可以拥有多个动作侦听器.实际上,你的班级不应该实现它.
首先删除actionPerformed
方法,然后替换此行:
Run Code Online (Sandbox Code Playgroud)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");
}
}
});
Run Code Online (Sandbox Code Playgroud)
您可以使用匿名类,按照此模式向计划添加的开始按钮添加另一个动作侦听器.(它不必是一个匿名类,这只是简单的演示.)