用Java构建一个计算表达式游戏
Java是一种基于类、面向对象的编程语言,旨在尽可能减少实现依赖项。为开发人员编写的一种通用编程语言,只要编写一次就可以在任何地方运行,编译后的Java代码可以在所有支持Java的平台上运行。 Java应用程序被编译成可以在任何Java虚拟机上运行的字节码。 Java的语法类似于 c/c++。
我们将在本文中构建什么?
什么是 2+3 ?是的,5是正确的! 5*8呢? 40,对!!计算它需要时间吗?让我们看看你和你的朋友在短短 60 秒内能做多少这样简单的问题。该游戏将让我们找出我们将能够在短短 60 秒内正确完成多少问题!为此,我们将使用Java swing 组件在Java中创建一个简单且基于时间的交互式“计算表达式游戏” 。下面给出了一个示例视频,以了解我们将在本文中做什么。
所以学习成果将是:
- 为我们的游戏创建交互式 GUI
- 两个JFrame的整合
- 工作定时器的创建
- 开发样式来管理组件
该项目将包含 3 个Java类:
- 主要的。Java
- 家。Java
- 玩。Java
我们将设计两个页面或我们所说的 JFrame。第一个 JFrame 将提供从游戏中播放或退出的选项。如果用户选择玩,第 2 个 JFrame 将包含玩家必须在 60 秒内回答最多基于数学表达式的问题的游戏。
分步实施
第 1 步。我们将首先导入此游戏所需的所有类。随着我们在这个项目中的进一步推进,我们将了解它们将如何发挥作用。
Java
// File name is Main.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
Java
// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
public class Main {
public static void main(String[] arg)
{
// to call the constructor of class Home
Home frame = new Home();
// Sets the title for this frame "HOME"
frame.setTitle("HOME");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
}
Java
// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
class Home extends JFrame implements ActionListener {
Home()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager() {}
public void setLocationAndSize() {}
public void addComponentsToContainer() {}
public void addActionEvent() {}
@Override public void actionPerformed(ActionEvent e) {}
}
public class Main {
public static void main(String[] arg)
{
// to call the constructor of class Home
Home frame = new Home();
// Sets the title for this frame "HOME"
frame.setTitle("HOME");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
}
Java
// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
class Home extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel home = new JLabel("HOME", JLabel.CENTER);
JButton playbutton = new JButton("PLAY");
JButton exitbutton = new JButton("EXIT");
Home()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager()
{
// Content panes use
// BorderLayout by default
container.setLayout(null);
}
public void setLocationAndSize()
{
// position and size of the components
// using setBounds(x,y,width,height)
home.setBounds(125, 20, 125, 30);
// to display content or BackGround
// behind a given component
home.setOpaque(true);
home.setBackground(Color.BLACK);
home.setForeground(Color.WHITE);
playbutton.setBounds(75, 200, 225, 30);
exitbutton.setBounds(75, 250, 225, 30);
}
public void addComponentsToContainer()
{
container.add(home);
container.add(playbutton);
container.add(exitbutton);
}
public void addActionEvent()
{
// listen for changes on the object
playbutton.addActionListener(this);
exitbutton.addActionListener(this);
}
@Override public void actionPerformed(ActionEvent e) {}
}
public class Main {
public static void main(String[] arg)
{
// to call the constructor of class Home
Home frame = new Home();
// Sets the title for this frame "HOME"
frame.setTitle("HOME");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
}
Java
// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
class Home extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel home = new JLabel("HOME", JLabel.CENTER);
JButton playbutton = new JButton("PLAY");
JButton exitbutton = new JButton("EXIT");
Home()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager()
{
// Content panes use BorderLayout by default
container.setLayout(null);
}
public void setLocationAndSize()
{
// position and size of the components
// using setBounds(x,y,width,height)
home.setBounds(125, 20, 125, 30);
// to display content or BackGround
// behind a given component
home.setOpaque(true);
home.setBackground(Color.BLACK);
home.setForeground(Color.WHITE);
playbutton.setBounds(75, 200, 225, 30);
exitbutton.setBounds(75, 250, 225, 30);
}
public void addComponentsToContainer()
{
container.add(home);
container.add(playbutton);
container.add(exitbutton);
}
public void addActionEvent()
{
// listen for changes on the object
playbutton.addActionListener(this);
exitbutton.addActionListener(this);
}
@Override public void actionPerformed(ActionEvent e)
{
if (e.getSource() == playbutton) {
// dispose() method clear
// resources at each frame
dispose();
// to call the constructor of class Play
Play frame = new Play();
// Sets the title for this frame "PLAY"
frame.setTitle("PLAY");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame using
// setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
if (e.getSource() == exitbutton) {
// asks for confirmation from the user to exit
// or not
int option = JOptionPane.showConfirmDialog(
this, "Do You Really Want To Quit",
"Thank you", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (option == JOptionPane.YES_OPTION) {
dispose();
}
}
}
}
public class Main {
public static void main(String[] arg)
{
// to call the constructor of class Home
Home frame = new Home();
// Sets the title for this frame "HOME"
frame.setTitle("HOME");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(
JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
}
Java
int Calculate(){
int num1 = new Random().nextInt(11); // 0 to 10
int num2 = new Random().nextInt(11) + 1; // 1 to 11
String operator = "+-/*%";
int random_operator = new Random().nextInt(5);
questiontext.setText("(" + num1 + ") " + operator.charAt(random_operator) + " (" + num2 + ")");
return switch (operator.charAt(random_operator)) {
case ('+') -> num1 + num2;
case ('-') -> num1 - num2;
case ('*') -> num1 * num2;
case ('/') -> num1 / num2;
case ('%') -> num1 % num2;
default -> 0;
};
}
Java
void Score(){
score += 1;
presentscoretext.setText(" " +score + " ");
}
Java
// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
class Game extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel questionlabel = new JLabel("QUESTION : ");
JTextField questiontext = new JTextField();
JLabel answerlabel = new JLabel("ANSWER : ");
JTextField answertext = new JTextField();
JLabel presentscorelabel
= new JLabel("PRESENT SCORE : ");
JTextField presentscoretext = new JTextField();
int result = 0;
int score = -1;
Timer gametimer;
// GAME TIMER in seconds
int start = 60;
Game()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
result = Calculate();
Score();
setTimer();
}
public void setLayoutManager()
{
container.setLayout(null);
}
public void setLocationAndSize()
{
questionlabel.setBounds(100, 100, 150, 30);
questiontext.setBounds(100, 140, 150, 30);
answerlabel.setBounds(100, 200, 150, 30);
answertext.setBounds(100, 240, 150, 30);
presentscorelabel.setBounds(100, 290, 150, 30);
presentscoretext.setBounds(100, 330, 150, 30);
}
public void addComponentsToContainer()
{
container.add(questionlabel);
container.add(questiontext);
container.add(answerlabel);
container.add(answertext);
container.add(presentscorelabel);
container.add(presentscoretext);
}
public void addActionEvent()
{
questiontext.setEditable(false);
presentscoretext.setEditable(false);
answertext.addActionListener(this);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent evt)
{
super.windowOpened(evt);
answertext.requestFocus();
}
});
}
public void setTimer()
{
gametimer = new Timer(1000, this);
gametimer.start();
}
@Override public void actionPerformed(ActionEvent e1) {}
}
class Home extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel home = new JLabel("HOME", JLabel.CENTER);
JButton playbutton = new JButton("PLAY");
JButton exitbutton = new JButton("EXIT");
Home()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager()
{
// Content panes use
// BorderLayout by default
container.setLayout(null);
}
public void setLocationAndSize()
{
// position and size of the components
// using setBounds(x,y,width,height)
home.setBounds(125, 20, 125, 30);
// to display content or BackGround
// behind a given component
home.setOpaque(true);
home.setBackground(Color.BLACK);
home.setForeground(Color.WHITE);
playbutton.setBounds(75, 200, 225, 30);
exitbutton.setBounds(75, 250, 225, 30);
}
public void addComponentsToContainer()
{
container.add(home);
container.add(playbutton);
container.add(exitbutton);
}
public void addActionEvent()
{
// listen for changes on the object
playbutton.addActionListener(this);
exitbutton.addActionListener(this);
}
@Override public void actionPerformed(ActionEvent e)
{
if (e.getSource() == playbutton) {
// dispose() method clear resources at each
// frame
dispose();
// to call the constructor of class Play
Game frame = new Game();
// Sets the title for this frame "PLAY"
frame.setTitle("PLAY");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
if (e.getSource() == exitbutton) {
// asks for confirmation from the user to exit
// or not
int option = JOptionPane.showConfirmDialog(
this, "Do You Really Want To Quit",
"Thank you", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (option == JOptionPane.YES_OPTION) {
dispose();
}
}
}
}
public class Main {
public static void main(String[] arg)
{
// to call the constructor of class Home
Home frame = new Home();
// Sets the title for this frame "HOME"
frame.setTitle("HOME");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
}
Java
// File name is Main.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;
class Game extends JFrame implements ActionListener{
Container container = getContentPane();
JLabel questionlabel = new JLabel("QUESTION : ");
JTextField questiontext = new JTextField();
JLabel answerlabel = new JLabel("ANSWER : ");
JTextField answertext = new JTextField();
JLabel presentscorelabel = new JLabel("PRESENT SCORE : ");
JTextField presentscoretext = new JTextField();
int result = 0;
int score = -1;
Timer gametimer;
// GAME TIMER in seconds
int start = 60;
Game(){
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
result = Calculate();
Score();
setTimer();
}
public void setLayoutManager() {
container.setLayout(null);
}
public void setLocationAndSize() {
questionlabel.setBounds(100, 100, 150, 30);
questiontext.setBounds(100, 140, 150, 30);
answerlabel.setBounds(100, 200, 150, 30);
answertext.setBounds(100, 240, 150, 30);
presentscorelabel.setBounds(100, 290, 150, 30);
presentscoretext.setBounds(100, 330, 150, 30);
}
public void addComponentsToContainer() {
container.add(questionlabel);
container.add(questiontext);
container.add(answerlabel);
container.add( answertext);
container.add(presentscorelabel);
container.add( presentscoretext);
}
public void addActionEvent() {
questiontext.setEditable(false);
presentscoretext.setEditable(false);
answertext.addActionListener(this);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent evt) {
super.windowOpened(evt);
answertext.requestFocus();
}
});
}
public void setTimer(){
gametimer = new Timer(1000,this);
gametimer.start();
}
@Override
public void actionPerformed(ActionEvent e1) {
start -= 1;
if(start >= 0){
try{
String s = e1.getActionCommand();
if(result == Integer.parseInt(s)){
Score();
}
result = Calculate();
answertext.setText(null);
}
catch(Exception e3){
}
}else{
gametimer.stop();
JOptionPane.showMessageDialog(this,"TIME IS UP. YOUR SCORE IS : " + score ,"SCORE",JOptionPane.PLAIN_MESSAGE);
int option = JOptionPane.showConfirmDialog(this,"DO YOU WANT TO PLAY AGAIN ?","PLAY AGAIN SCORE : " + score,JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
if(option == JOptionPane.YES_OPTION){
dispose();
Game frame = new Game();
frame.setTitle("PLAY");
frame.setVisible(true);
frame.setBounds(10,10,370,600);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setResizable(false);
}
else{
dispose();
Home frame = new Home();
frame.setTitle("HOME");
frame.setVisible(true);
frame.setBounds(10,10,370,600);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setResizable(false);
}
}
}
int Calculate(){
int num1 = new Random().nextInt(11); // 1 to 10
int num2 = new Random().nextInt(11) + 1; // 0 to 10
String operator = "+-/*%";
int random_operator = new Random().nextInt(5);
questiontext.setText("(" + num1 + ") " + operator.charAt(random_operator) + " (" + num2 + ")");
return switch (operator.charAt(random_operator)) {
case ('+') -> num1 + num2;
case ('-') -> num1 - num2;
case ('*') -> num1 * num2;
case ('/') -> num1 / num2;
case ('%') -> num1 % num2;
default -> 0;
};
}
void Score(){
score += 1;
presentscoretext.setText(" " +score + " ");
}
}
class Home extends JFrame implements ActionListener{
Container container = getContentPane();
JLabel home = new JLabel("HOME",JLabel.CENTER);
JButton playbutton = new JButton("PLAY");
JButton exitbutton = new JButton("EXIT");
Home(){
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager(){
// Content panes use
// BorderLayout by default
container.setLayout(null);
}
public void setLocationAndSize(){
// position and size of the components
// using setBounds(x,y,width,height)
home.setBounds(125,20,125,30);
// to display content or BackGround
// behind a given component
home.setOpaque(true);
home.setBackground(Color.BLACK);
home.setForeground(Color.WHITE);
playbutton.setBounds(75,200,225,30);
exitbutton.setBounds(75,250,225,30);
}
public void addComponentsToContainer(){
container.add(home);
container.add(playbutton);
container.add(exitbutton);
}
public void addActionEvent(){
// listen for changes on the object
playbutton.addActionListener(this);
exitbutton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource() == playbutton){
// dispose() method clear
// resources at each frame
dispose();
// to call the constructor of class Play
Game frame = new Game();
// Sets the title for this frame "PLAY"
frame.setTitle("PLAY");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10,10,370,600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
if(e.getSource() == exitbutton){
// asks for confirmation from the user to exit or not
int option = JOptionPane.showConfirmDialog(this,"Do You Really Want To Quit","Thank you", JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE);
if(option == JOptionPane.YES_OPTION){
dispose();
}
}
}
}
public class MAN {
public static void main(String[] arg){
// to call the constructor of class Home
Home frame = new Home();
// Sets the title for this frame "HOME"
frame.setTitle("HOME");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10,10,370,600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
}
第 2 步。我们将定义一个 Main 类,该类将调用 Home Constructor 类。
Java
// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
public class Main {
public static void main(String[] arg)
{
// to call the constructor of class Home
Home frame = new Home();
// Sets the title for this frame "HOME"
frame.setTitle("HOME");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
}
第 3 步。我们现在将定义我们的类 Home 并为其准备一个样式,以便跟踪组件不会让我们的头脑变得混乱。另外,是时候弄清楚一些概念了!我们将继承 JFrame 类,它是一个 swing 组件(javax.swing 包的一部分)。为了定义用户执行某些操作时应该做什么,我们将实现 ActionListener 接口。 ActionListener(在Java.awt.event 包中找到)只有一个方法 actionPerformed(ActionEvent),当用户执行某些操作时会调用该方法。
Java
// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
class Home extends JFrame implements ActionListener {
Home()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager() {}
public void setLocationAndSize() {}
public void addComponentsToContainer() {}
public void addActionEvent() {}
@Override public void actionPerformed(ActionEvent e) {}
}
public class Main {
public static void main(String[] arg)
{
// to call the constructor of class Home
Home frame = new Home();
// Sets the title for this frame "HOME"
frame.setTitle("HOME");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
}
第 4 步。我们将定义组件并将它们添加到 Home 框架。
Java
// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
class Home extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel home = new JLabel("HOME", JLabel.CENTER);
JButton playbutton = new JButton("PLAY");
JButton exitbutton = new JButton("EXIT");
Home()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager()
{
// Content panes use
// BorderLayout by default
container.setLayout(null);
}
public void setLocationAndSize()
{
// position and size of the components
// using setBounds(x,y,width,height)
home.setBounds(125, 20, 125, 30);
// to display content or BackGround
// behind a given component
home.setOpaque(true);
home.setBackground(Color.BLACK);
home.setForeground(Color.WHITE);
playbutton.setBounds(75, 200, 225, 30);
exitbutton.setBounds(75, 250, 225, 30);
}
public void addComponentsToContainer()
{
container.add(home);
container.add(playbutton);
container.add(exitbutton);
}
public void addActionEvent()
{
// listen for changes on the object
playbutton.addActionListener(this);
exitbutton.addActionListener(this);
}
@Override public void actionPerformed(ActionEvent e) {}
}
public class Main {
public static void main(String[] arg)
{
// to call the constructor of class Home
Home frame = new Home();
// Sets the title for this frame "HOME"
frame.setTitle("HOME");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
}
第 5 步。是时候为按钮添加功能了。
Java
// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
class Home extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel home = new JLabel("HOME", JLabel.CENTER);
JButton playbutton = new JButton("PLAY");
JButton exitbutton = new JButton("EXIT");
Home()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager()
{
// Content panes use BorderLayout by default
container.setLayout(null);
}
public void setLocationAndSize()
{
// position and size of the components
// using setBounds(x,y,width,height)
home.setBounds(125, 20, 125, 30);
// to display content or BackGround
// behind a given component
home.setOpaque(true);
home.setBackground(Color.BLACK);
home.setForeground(Color.WHITE);
playbutton.setBounds(75, 200, 225, 30);
exitbutton.setBounds(75, 250, 225, 30);
}
public void addComponentsToContainer()
{
container.add(home);
container.add(playbutton);
container.add(exitbutton);
}
public void addActionEvent()
{
// listen for changes on the object
playbutton.addActionListener(this);
exitbutton.addActionListener(this);
}
@Override public void actionPerformed(ActionEvent e)
{
if (e.getSource() == playbutton) {
// dispose() method clear
// resources at each frame
dispose();
// to call the constructor of class Play
Play frame = new Play();
// Sets the title for this frame "PLAY"
frame.setTitle("PLAY");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame using
// setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
if (e.getSource() == exitbutton) {
// asks for confirmation from the user to exit
// or not
int option = JOptionPane.showConfirmDialog(
this, "Do You Really Want To Quit",
"Thank you", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (option == JOptionPane.YES_OPTION) {
dispose();
}
}
}
}
public class Main {
public static void main(String[] arg)
{
// to call the constructor of class Home
Home frame = new Home();
// Sets the title for this frame "HOME"
frame.setTitle("HOME");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(
JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
}
第 6 步。让我们看看将用于我们的项目的两个实用程序函数。计算函数以生成数学表达式。在这里,我们使用给定范围内的导入类 import Java.util.Random 生成两个随机数。
Java
int Calculate(){
int num1 = new Random().nextInt(11); // 0 to 10
int num2 = new Random().nextInt(11) + 1; // 1 to 11
String operator = "+-/*%";
int random_operator = new Random().nextInt(5);
questiontext.setText("(" + num1 + ") " + operator.charAt(random_operator) + " (" + num2 + ")");
return switch (operator.charAt(random_operator)) {
case ('+') -> num1 + num2;
case ('-') -> num1 - num2;
case ('*') -> num1 * num2;
case ('/') -> num1 / num2;
case ('%') -> num1 % num2;
default -> 0;
};
}
得分函数显示球员的更新得分。
Java
void Score(){
score += 1;
presentscoretext.setText(" " +score + " ");
}
第 7 步。现在我们将定义 Play 类的骨架。
在这里,我们使用 WindowActionListener 请求将 JFrame 对象的焦点放在文本字段上。此外,我们正在创建一个 60 秒的 TIMER,以便在 60 秒的延迟后不会接受任何输入,这也将确保不超过 60 个输入(以防用户多次按下相同的输入) .在实践中,计时器在等待用户输入的 1000 毫秒延迟后运行,这就是为什么我们将 ActionEvent 包围在 try-catch 块中,以防用户在该特定秒内没有提供输入。
Java
// File name is Main.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.Random;
import javax.swing.*;
class Game extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel questionlabel = new JLabel("QUESTION : ");
JTextField questiontext = new JTextField();
JLabel answerlabel = new JLabel("ANSWER : ");
JTextField answertext = new JTextField();
JLabel presentscorelabel
= new JLabel("PRESENT SCORE : ");
JTextField presentscoretext = new JTextField();
int result = 0;
int score = -1;
Timer gametimer;
// GAME TIMER in seconds
int start = 60;
Game()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
result = Calculate();
Score();
setTimer();
}
public void setLayoutManager()
{
container.setLayout(null);
}
public void setLocationAndSize()
{
questionlabel.setBounds(100, 100, 150, 30);
questiontext.setBounds(100, 140, 150, 30);
answerlabel.setBounds(100, 200, 150, 30);
answertext.setBounds(100, 240, 150, 30);
presentscorelabel.setBounds(100, 290, 150, 30);
presentscoretext.setBounds(100, 330, 150, 30);
}
public void addComponentsToContainer()
{
container.add(questionlabel);
container.add(questiontext);
container.add(answerlabel);
container.add(answertext);
container.add(presentscorelabel);
container.add(presentscoretext);
}
public void addActionEvent()
{
questiontext.setEditable(false);
presentscoretext.setEditable(false);
answertext.addActionListener(this);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent evt)
{
super.windowOpened(evt);
answertext.requestFocus();
}
});
}
public void setTimer()
{
gametimer = new Timer(1000, this);
gametimer.start();
}
@Override public void actionPerformed(ActionEvent e1) {}
}
class Home extends JFrame implements ActionListener {
Container container = getContentPane();
JLabel home = new JLabel("HOME", JLabel.CENTER);
JButton playbutton = new JButton("PLAY");
JButton exitbutton = new JButton("EXIT");
Home()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager()
{
// Content panes use
// BorderLayout by default
container.setLayout(null);
}
public void setLocationAndSize()
{
// position and size of the components
// using setBounds(x,y,width,height)
home.setBounds(125, 20, 125, 30);
// to display content or BackGround
// behind a given component
home.setOpaque(true);
home.setBackground(Color.BLACK);
home.setForeground(Color.WHITE);
playbutton.setBounds(75, 200, 225, 30);
exitbutton.setBounds(75, 250, 225, 30);
}
public void addComponentsToContainer()
{
container.add(home);
container.add(playbutton);
container.add(exitbutton);
}
public void addActionEvent()
{
// listen for changes on the object
playbutton.addActionListener(this);
exitbutton.addActionListener(this);
}
@Override public void actionPerformed(ActionEvent e)
{
if (e.getSource() == playbutton) {
// dispose() method clear resources at each
// frame
dispose();
// to call the constructor of class Play
Game frame = new Game();
// Sets the title for this frame "PLAY"
frame.setTitle("PLAY");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
if (e.getSource() == exitbutton) {
// asks for confirmation from the user to exit
// or not
int option = JOptionPane.showConfirmDialog(
this, "Do You Really Want To Quit",
"Thank you", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (option == JOptionPane.YES_OPTION) {
dispose();
}
}
}
}
public class Main {
public static void main(String[] arg)
{
// to call the constructor of class Home
Home frame = new Home();
// Sets the title for this frame "HOME"
frame.setTitle("HOME");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10, 10, 370, 600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
}
第 8 步。我们现在处于最后一个阶段,我们将实用程序添加到源代码中,并添加两条消息,以便用户能够在 60 秒后查看分数,并要求用户再次播放。下面是这个游戏的工作源代码。
Java
// File name is Main.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;
class Game extends JFrame implements ActionListener{
Container container = getContentPane();
JLabel questionlabel = new JLabel("QUESTION : ");
JTextField questiontext = new JTextField();
JLabel answerlabel = new JLabel("ANSWER : ");
JTextField answertext = new JTextField();
JLabel presentscorelabel = new JLabel("PRESENT SCORE : ");
JTextField presentscoretext = new JTextField();
int result = 0;
int score = -1;
Timer gametimer;
// GAME TIMER in seconds
int start = 60;
Game(){
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
result = Calculate();
Score();
setTimer();
}
public void setLayoutManager() {
container.setLayout(null);
}
public void setLocationAndSize() {
questionlabel.setBounds(100, 100, 150, 30);
questiontext.setBounds(100, 140, 150, 30);
answerlabel.setBounds(100, 200, 150, 30);
answertext.setBounds(100, 240, 150, 30);
presentscorelabel.setBounds(100, 290, 150, 30);
presentscoretext.setBounds(100, 330, 150, 30);
}
public void addComponentsToContainer() {
container.add(questionlabel);
container.add(questiontext);
container.add(answerlabel);
container.add( answertext);
container.add(presentscorelabel);
container.add( presentscoretext);
}
public void addActionEvent() {
questiontext.setEditable(false);
presentscoretext.setEditable(false);
answertext.addActionListener(this);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent evt) {
super.windowOpened(evt);
answertext.requestFocus();
}
});
}
public void setTimer(){
gametimer = new Timer(1000,this);
gametimer.start();
}
@Override
public void actionPerformed(ActionEvent e1) {
start -= 1;
if(start >= 0){
try{
String s = e1.getActionCommand();
if(result == Integer.parseInt(s)){
Score();
}
result = Calculate();
answertext.setText(null);
}
catch(Exception e3){
}
}else{
gametimer.stop();
JOptionPane.showMessageDialog(this,"TIME IS UP. YOUR SCORE IS : " + score ,"SCORE",JOptionPane.PLAIN_MESSAGE);
int option = JOptionPane.showConfirmDialog(this,"DO YOU WANT TO PLAY AGAIN ?","PLAY AGAIN SCORE : " + score,JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
if(option == JOptionPane.YES_OPTION){
dispose();
Game frame = new Game();
frame.setTitle("PLAY");
frame.setVisible(true);
frame.setBounds(10,10,370,600);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setResizable(false);
}
else{
dispose();
Home frame = new Home();
frame.setTitle("HOME");
frame.setVisible(true);
frame.setBounds(10,10,370,600);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setResizable(false);
}
}
}
int Calculate(){
int num1 = new Random().nextInt(11); // 1 to 10
int num2 = new Random().nextInt(11) + 1; // 0 to 10
String operator = "+-/*%";
int random_operator = new Random().nextInt(5);
questiontext.setText("(" + num1 + ") " + operator.charAt(random_operator) + " (" + num2 + ")");
return switch (operator.charAt(random_operator)) {
case ('+') -> num1 + num2;
case ('-') -> num1 - num2;
case ('*') -> num1 * num2;
case ('/') -> num1 / num2;
case ('%') -> num1 % num2;
default -> 0;
};
}
void Score(){
score += 1;
presentscoretext.setText(" " +score + " ");
}
}
class Home extends JFrame implements ActionListener{
Container container = getContentPane();
JLabel home = new JLabel("HOME",JLabel.CENTER);
JButton playbutton = new JButton("PLAY");
JButton exitbutton = new JButton("EXIT");
Home(){
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();
}
public void setLayoutManager(){
// Content panes use
// BorderLayout by default
container.setLayout(null);
}
public void setLocationAndSize(){
// position and size of the components
// using setBounds(x,y,width,height)
home.setBounds(125,20,125,30);
// to display content or BackGround
// behind a given component
home.setOpaque(true);
home.setBackground(Color.BLACK);
home.setForeground(Color.WHITE);
playbutton.setBounds(75,200,225,30);
exitbutton.setBounds(75,250,225,30);
}
public void addComponentsToContainer(){
container.add(home);
container.add(playbutton);
container.add(exitbutton);
}
public void addActionEvent(){
// listen for changes on the object
playbutton.addActionListener(this);
exitbutton.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource() == playbutton){
// dispose() method clear
// resources at each frame
dispose();
// to call the constructor of class Play
Game frame = new Game();
// Sets the title for this frame "PLAY"
frame.setTitle("PLAY");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10,10,370,600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
if(e.getSource() == exitbutton){
// asks for confirmation from the user to exit or not
int option = JOptionPane.showConfirmDialog(this,"Do You Really Want To Quit","Thank you", JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE);
if(option == JOptionPane.YES_OPTION){
dispose();
}
}
}
}
public class MAN {
public static void main(String[] arg){
// to call the constructor of class Home
Home frame = new Home();
// Sets the title for this frame "HOME"
frame.setTitle("HOME");
// Component will be displayed on the screen
frame.setVisible(true);
// position and size of the frame
// using setBounds(x,y,width,height)
frame.setBounds(10,10,370,600);
// application exits on close window
// event from the operating system
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// user cannot re-size the frame
frame.setResizable(false);
}
}
输出: