题目:
编写一个包含主方法main的公共类(访问权限为public的类),该类继承自窗体类JFrame,并且,该类实现了接口ActionListener(实现接口ActionListener的方法actionPerformed)。
实现图形用户界面(当窗口大小改变时,第1行和第2行的组件的大小也会随之改变,其他组件的大小不发生改变),并且完成以下要求:
(1)窗体的标题是“猜数字小游戏”。
(2)单击“得到一个随机数”按钮,系统产生一个1~10之间的随机整数。(使用Math类的方法random( ))
(3)在“输入您的猜测:”后面的文本框中输入你要猜测的整数,之后单击“确定”按钮。
(4)对猜测的整数,图形用户界面的最下面会有提示信息:没有猜的时候,显示“无反馈信息”;如果猜大了,显示“猜大了”;如果猜小了,显示“猜小了”;如果猜对了,显示“猜对了”。(蓝色字体通过JLabel类的对象调用方法setForeground(Color.blue)实现)
审题:
当窗口大小改变时,第1行和第2行的组件的大小也会随之改变——GridLayout布局;其他组件的大小不发生改变——FlowLayout布局。
//图形用户界面
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//又是窗体又是监听器
class GuessNumberGame extends JFrame implements ActionListener {
int num;
//创建按钮
JButton getNum = new JButton("得到一个随机数");
JButton enterButton = new JButton("确定");
//创建文本框
JTextField inputNum = new JTextField();
//创建标签对象(标签用来显示信息)
JLabel fanKui = new JLabel("无反馈信息");
GuessNumberGame() {
setLayout(new GridLayout(3, 1)); //对窗体的默认布局进行更改
fanKui.setForeground(Color.blue);
//向按钮增加监视器
//this是窗体对象本身
getNum.addActionListener(this);
enterButton.addActionListener(this);
//将JPanel类的对象作为一个整体添加到窗体或其它容器中
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(2, 2, 0, 5));
p1.add(new JLabel(" 获取 [1, 10] 之间的随机数:"));
p1.add(getNum);
p1.add(new JLabel(" 输入您的猜测:"));
p1.add(inputNum);
JPanel p2 = new JPanel();
//FlowLayout()组件大小不会随窗体的大小的改变而改变
p2.setLayout(new FlowLayout());
p2.add(new JLabel("单击确定按钮:"));
p2.add(enterButton);
JPanel p3 = new JPanel();
p3.setLayout(new FlowLayout());
p3.add(fanKui);
add(p1);
add(p2);
add(p3);
setTitle("猜数字小游戏");
setBounds(100, 100, 400, 200);
setVisible(true); //默认不可见
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//实现接口的抽象方法
//单击按钮时触发ActionEvent事件
public void actionPerformed(ActionEvent ae) {
JButton button = (JButton)ae.getSource(); //获取事件源
if(button == getNum) {
num = (int)(Math.random()*9)+1;
}
if(button == enterButton) {
int temp;
String s = inputNum.getText();
temp = Integer.parseInt(s);
if(temp == num) {
fanKui.setText("猜对了");
}
else if(temp < num) {
fanKui.setText("猜小了");
}
else {
fanKui.setText("猜大了");
}
}
}
public static void main(String[] args) {
new GuessNumberGame();
}
}