package homework;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.*;
public class GameTest {
public static void main(String[] args) {
// TODO 自動生成的方法存根
GameFrame gf = new GameFrame();
double width = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
double height = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
gf.setLocation((int) (width - gf.getWidth()) / 2, (int) (height - gf.getHeight()) / 2);
}
}
class GameFrame extends JFrame implements ActionListener {
// 聲明標簽
JLabel Getlb;// 1到100之間隨機數標簽
JLabel Inputlb;// 請輸入猜測數標簽
JLabel Clicklb;// 單擊確定按鈕標簽
JLabel Infolb;// 反饋信息標簽
JLabel Rightlb;// 實時反饋結果標簽
JTextField jtf;// 輸入猜測數字文本框
int number;// 我猜的數字
// 聲明初始化按鈕
JButton getButton = new JButton("得到一個隨機數");// 獲取隨機數按鈕
JButton confButton = new JButton("確定");// 確定按鈕
FlowLayout g = new FlowLayout(FlowLayout.LEFT, 10, 10);
// 聲明面板
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p5 = new JPanel();
JPanel p6 = new JPanel();
JPanel p7 = new JPanel();
JPanel p8 = new JPanel();
Border e = BorderFactory.createEtchedBorder();
public GameFrame() {
this.setSize(400, 300);
this.setTitle("猜數字小游戲");
Container c = this.getContentPane();
GridLayout f = new GridLayout(4, 2, 10, 10);
c.setLayout(f);
Getlb = new JLabel("獲得1到100之間的隨機數:");
Inputlb = new JLabel("請輸入你的猜測:");
Clicklb = new JLabel("單擊確定按鈕:");
Infolb = new JLabel("反饋信息:");
Rightlb = new JLabel();
jtf = new JTextField(15);
p1.setLayout(g);
p3.setLayout(g);
p5.setLayout(g);
p7.setLayout(g);
getButton.setSize(100, 100);
p1.add(Getlb);
p2.setBorder(e);
p2.add(getButton);
p3.add(Inputlb);
p4.setBorder(e);
p4.add(jtf);
p5.add(Clicklb);
p6.setBorder(e);
p6.add(confButton);
p7.add(Infolb);
p8.add(Rightlb);
c.add(p1);
c.add(p2);
c.add(p3);
c.add(p4);
c.add(p5);
c.add(p6);
c.add(p7);
c.add(p8);
// 設置程序可視化及關閉
this.setVisible(true);
this.setDefaultCloseOperation(3);
// 給按鈕設置監聽器
getButton.addActionListener(this);
confButton.addActionListener(this);
}
// 實現actionPerformed接口方法
public void actionPerformed(ActionEvent e) {
// TODO 自動生成的方法存根
int count = 0;// 初始化計數器
if (e.getSource() == getButton) {
number = (int) (Math.random() * 100) + 1;
getButton.setEnabled(false);
}
if (e.getSource() == confButton) {
int guessnumber = Integer.parseInt(jtf.getText());
if (guessnumber > number) {
Rightlb.setText("猜大了!");
}
if (guessnumber < number) {
Rightlb.setText("猜小了!");
}
if (guessnumber==number) {
Rightlb.setText("猜對了!你一共猜了" + count + "次");
}
}
}
}
想了好幾種方法都不行,如何設置計數器統計猜測次數呢?
類中定義一個 靜態 int 變量,每次猜測的時候,++就好了