21xrx.com
2025-03-29 05:42:22 Saturday
文章检索 我的文章 写文章
Java GUI编程实例:计算器和飞机大战游戏
2023-06-18 01:06:06 深夜i     19     0
Java GUI编程

我最近在学习Java GUI编程,并尝试了一些实例。

首先,我写了一个简单的计算器程序。下面是代码例子:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener{
  private JTextField inputField;
  private JButton[] btns;
  private String[] btnValues = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
  private boolean isFirstInput = true;
  private String operator = "";
  private double result = 0;
  public Calculator(){
    setTitle("Calculator");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(180, 220);
    setResizable(false);
    inputField = new JTextField(15);
    inputField.setHorizontalAlignment(JTextField.RIGHT);
    inputField.setEditable(false);
    JPanel btnPanel = new JPanel();
    btnPanel.setLayout(new GridLayout(4, 4));
    btns = new JButton[16];
    for(int i=0; i
      btns[i] = new JButton(btnValues[i]);
      btns[i].addActionListener(this);
      btnPanel.add(btns[i]);
    }
    add(inputField, BorderLayout.NORTH);
    add(btnPanel, BorderLayout.CENTER);
    setVisible(true);
  }
  @Override
  public void actionPerformed(ActionEvent e){
    String input = e.getActionCommand();
    if(isFirstInput){
      inputField.setText("");
      isFirstInput = false;
    }
    if(input.equals("+") || input.equals("-") || input.equals("*") || input.equals("/")){
      operator = input;
      result = Double.parseDouble(inputField.getText());
      isFirstInput = true;
    }
    else if(input.equals("=")){
      double secondNum = Double.parseDouble(inputField.getText());
      if(operator.equals("+"))
        result += secondNum;
      else if(operator.equals("-"))
        result -= secondNum;
      else if(operator.equals("*"))
        result *= secondNum;
      else if(operator.equals("/"))
        result /= secondNum;
      inputField.setText(result + "");
      isFirstInput = true;
    }
    else{
      inputField.setText(inputField.getText() + input);
    }
  }
  public static void main(String[] args){
    new Calculator();
  }
}

运行程序,可以看到一个简单的计算器界面,支持加减乘除四则运算。

另外一个例子是一个简单的飞机大战游戏。下面是代码例子:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
public class PlaneGame extends JFrame implements ActionListener{
  private JPanel gamePanel;
  private Timer timer;
  private ArrayList
  planes;
 
  private ArrayList
  bullets;
 
  private MyPlane myPlane;
  private int score = 0;
  public PlaneGame(){
    setTitle("Plane Game");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    setSize(600, 680);
    gamePanel = new JPanel(){
      @Override
      protected void paintComponent(Graphics g){
        super.paintComponent(g);
        for(Plane p: planes)
          p.draw(g);
        for(Bullet b: bullets)
          b.draw(g);
        if(myPlane != null)
          myPlane.draw(g);
        drawScore(g);
      }
    };
    gamePanel.setBackground(Color.WHITE);
    gamePanel.setLayout(null);
    add(gamePanel, BorderLayout.CENTER);
    timer = new Timer(10, this);
    planes = new ArrayList<>();
    bullets = new ArrayList<>();
    setVisible(true);
    startGame();
  }
  private void startGame(){
    myPlane = new MyPlane(gamePanel.getWidth() / 2 - 20, gamePanel.getHeight() - 100);
    planes.add(new EnemyPlane(50, 30));
    planes.add(new EnemyPlane(250, 10));
    planes.add(new EnemyPlane(450, 20));
    timer.start();
  }
  private void drawScore(Graphics g){
    g.setColor(Color.BLUE);
    g.setFont(new Font("Arial", Font.BOLD, 24));
    g.drawString("Score: " + score, 10, 30);
  }
  @Override
  public void actionPerformed(ActionEvent e){
    if(e.getSource() == timer){
      for(Plane p: planes)
        p.move(gamePanel);
      for(Bullet b: bullets)
        b.move();
      checkCollision();
      gamePanel.repaint();
      if(new Random().nextInt(100) < 5)
        planes.add(new EnemyPlane(new Random().nextInt(gamePanel.getWidth() - 60), 30));
      if(score >= 100)
        timer.stop();
    }
  }
  private void checkCollision(){
    for(Plane p: planes){
      if(!p.isAlive())
        continue;
      if(myPlane.hitTest(p)){
        myPlane.setAlive(false);
        timer.stop();
        JOptionPane.showMessageDialog(this, "Game Over!");
        return;
      }
      for(Bullet b: bullets){
        if(b.hitTest(p)){
          p.setAlive(false);
          b.setAlive(false);
          score++;
          break;
        }
      }
    }
    bullets.removeIf(b -> !b.isAlive());
    planes.removeIf(p -> !p.isAlive() && !(p instanceof MyPlane));
  }
  public static void main(String[] args){
    new PlaneGame();
  }
}
abstract class Plane{
  protected int x, y, width, height;
  protected Image image;
  protected boolean alive = true;
  public Plane(int x, int y, int width, int height, String imageUrl){
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    image = new ImageIcon(getClass().getResource(imageUrl)).getImage();
  }
  public void move(JPanel container){
    y += 5;
    if(y > container.getHeight())
      alive = false;
  }
  public void draw(Graphics g){
    if(alive)
      g.drawImage(image, x, y, width, height, null);
  }
  public boolean isAlive()
    return alive;
  
  public void setAlive(boolean alive)
    this.alive = alive;
  
  public boolean hitTest(Plane plane){
    return x + width > plane.x && x < plane.x + plane.width && y + height > plane.y && y < plane.y + plane.height;
  }
}
class MyPlane extends Plane{
  public MyPlane(int x, int y){
    super(x, y, 40, 40, "/images/my_plane.png");
  }
}
class EnemyPlane extends Plane{
  public EnemyPlane(int x, int y){
    super(x, y, 60, 45, "/images/enemy_plane.png");
  }
  public EnemyPlane(int x, int y, int width, int height, String imageUrl){
    super(x, y, width, height, imageUrl);
  }
  @Override
  public void move(JPanel container){
    y += 10;
    if(y > container.getHeight())
      alive = false;
  }
}
class Bullet{
  private int x, y, speed;
  private Image image;
  private boolean alive = true;
  public Bullet(int x, int y, int speed){
    this.x = x;
    this.y = y;
    this.speed = speed;
    image = new ImageIcon(getClass().getResource("/images/bullet.png")).getImage();
  }
  public void move(){
    y -= speed;
    if(y < -10)
      alive = false;
  }
  public void draw(Graphics g){
    if(alive)
      g.drawImage(image, x, y, 10, 10, null);
  }
  public boolean isAlive()
    return alive;
  
  public void setAlive(boolean alive)
    this.alive = alive;
  
  public boolean hitTest(Plane plane){
    return x + 10 > plane.x && x < plane.x + plane.width && y + 10 > plane.y && y < plane.y + plane.height;
  }
}

运行程序,可以看到一个简单的飞机大战游戏界面。

三个 、计算器、飞机大战游戏。

一个

  
  
下一篇: main函数

评论区