自学内容网 自学内容网

Java GUI制作双人对打游戏


前言

什么是Java GUI

Java UI,即Java用户界面,是指使用Java编程语言创建的图形用户界面(GUI)。Java提供了多种工具和技术来创建和管理用户界面,使得开发者能够构建具有丰富交互性和吸引力的应用程序。

在Java中,用于构建UI的主要库和框架包括:

Swing:Swing是Java平台标准版(Java SE)的一部分,它提供了一组丰富的GUI组件和布局管理器,用于构建跨平台的桌面应用程序。Swing组件包括按钮、文本框、标签、滑块等,以及更复杂的组件如表格和树形结构。
JavaFX:JavaFX是一个用于构建富客户端应用程序的图形和媒体库。它提供了现代化的UI组件、动画、Web集成和媒体支持。与Swing相比,JavaFX更加现代和灵活,适用于构建复杂的用户界面和多媒体应用程序。
AWT:AWT(Abstract Window Toolkit)是Java中最早的GUI工具包,提供了基本的窗口、按钮和文本框等组件。然而,随着Swing和JavaFX的出现,AWT的使用逐渐减少,但仍在一些旧的或特定的应用程序中使用。
在构建Java UI时,开发者通常会遵循以下步骤:

设计界面:首先,开发者需要设计应用程序的用户界面,确定所需的组件、布局和交互方式。
选择库和框架:根据应用程序的需求和目标平台,选择适合的Java UI库和框架。
创建组件:使用所选库和框架提供的API创建所需的UI组件,并设置它们的属性(如大小、颜色、字体等)。
布局管理:使用布局管理器来组织和管理组件在界面上的位置和大小。Java提供了多种布局管理器,如边界布局、网格布局和流式布局等。
事件处理:为组件添加事件监听器,以便在用户与界面交互时执行相应的操作(如点击按钮、选择菜单项等)。
测试和调试:在开发过程中不断测试和调试UI,确保其正常运行并符合设计要求。
通过Java UI技术,开发者可以创建出功能强大、外观美观的应用程序,提供丰富的用户体验。这些应用程序可以运行在桌面、移动设备或其他Java支持的平台上。

在这里插入图片描述

上图是制作成功的效果图 通过A、D来控制蓝色人物前进防御和后退,J、K、L来控制拳、防御、踢腿
红色人物对应的是左箭头、右箭头以及1、2、3.


制作这个小游戏 作者打算用2篇博文来分享整个过程 本文作为一个引入

一、打开IDEA 新建一个Maven项目(后续可以打包、引入相关依赖也很容易)

建完之后的整体结构如下:
在这里插入图片描述

二、引入依赖

因为需要播放MP3格式的背景音乐于是要引入相关依赖:
在pom.xml中添加下面的代码

    <dependencies>
        <dependency>
            <groupId>javazoom</groupId>
            <artifactId>jlayer</artifactId>
            <version>1.0.1</version>
        </dependency>

    </dependencies>

三.绘制UI界面

代码如下:

package src;
import javazoom.jl.player.Player;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
public class UI extends JFrame implements KeyListener {
    WarPanel warPanel=new WarPanel();
    Player player;
    public UI(){
        this.setTitle("赤色妖精花2.0");
        this.setLocation(0,0);
        this.setSize(1024,680);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        this.add(warPanel);
        this.addKeyListener(this);
        warPanel.action();
    }
    public static void main(String[] args) {
        UI ui=new UI();
        ui.init();
    }
    public void init(){
        while(true)
        {
            try
            {
               InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/bgm12.mp3");
             playmusic(resourceAsStream);
                Thread.sleep(82800);
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    public void playmusic(InputStream inputStream) throws Exception{
//        BufferedInputStream bufferedInputStream=new BufferedInputStream(inputStream);
        player=new Player(inputStream);
        player.play();
    }
    public void playmusic(String music) throws Exception{
        BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(music));
        player=new Player(bufferedInputStream);
        player.play();
    }
    public void sound(String str)
    {
        try {
            FileInputStream in = new FileInputStream(str);
            AudioStream as=new
                    AudioStream(in);
            AudioPlayer.player.start(as);
        }catch(Exception e)
        {
            e.printStackTrace();
        }
}
    public void sound(InputStream inputStream)
    {
        try {
            AudioStream as=new
                    AudioStream(inputStream);
            AudioPlayer.player.start(as);
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
//        System.out.println(e.getKeyCode());
        warPanel.restart(e.getKeyCode());
        warPanel.manmove(e.getKeyCode());
        warPanel.mastermove(e.getKeyCode());

    }

    @Override
    public void keyReleased(KeyEvent e) {
        warPanel.mastercancel(e.getKeyCode());
        warPanel.mancancel(e.getKeyCode());

    }
}

四.绘制JPanel面板

JPanel是Java Swing库中的一个关键组件,它提供了许多优点,使得开发者能够更高效地创建复杂的图形用户界面(GUI)。以下是JPanel的一些主要优点:
轻量级容器:JPanel是一个轻量级的容器,这意味着它使用了本地窗口系统的较少资源,因此更加高效。轻量级组件的绘制通常比重量级组件更快,并且更易于管理。
灵活的布局管理:JPanel允许使用各种布局管理器来控制其内部组件的布局。例如,你可以使用FlowLayout、BorderLayout、GridLayout等,这使得开发者能够轻松地排列和调整组件的位置和大小,以满足不同的界面设计需求。
嵌套和组合:JPanel可以嵌套在其他Swing容器中,如JFrame、JDialog等,这使得开发者能够创建复杂的界面结构。通过组合多个JPanel,你可以实现更精细的界面布局和组件组织。
事件处理:JPanel支持事件监听器,使得开发者能够响应用户与界面的交互,如按钮点击、鼠标移动等。这使得应用程序能够更加响应用户的操作,提供更好的用户体验。
自定义绘制:JPanel提供了绘制自定义图形、图像或文本的功能。你可以通过重写paintComponent方法来实现自定义绘制逻辑,从而创建独特的视觉效果。
易于扩展和集成:由于JPanel是Swing库的一部分,它与其他Swing组件具有良好的集成性。此外,由于其开源性质,开发者可以根据需要扩展JPanel的功能,以满足特定的应用需求。
综上所述,JPanel作为Java Swing库中的一个核心组件,具有轻量级、灵活布局、嵌套组合、事件处理、自定义绘制以及易于扩展和集成等优点,使得开发者能够高效地创建复杂的图形用户界面。

package src;

import javazoom.jl.player.Player;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

public class WarPanel extends JPanel {
    private static String LEFT="left";
    private static String RIGHT="right";
    private static String STATIC="static";
    String path=null;
    int x;
    int y;
    int bloodMan=430;
    int bloodMaster=413;
    int time=600;
    InputStream AsStream=this.getClass().getClassLoader().getResourceAsStream("music/victorymaster.mp3");
    InputStream AsStream1=this.getClass().getClassLoader().getResourceAsStream("music/victoryman.mp3");

    SuperMan superMan=new SuperMan();
    Matser matser=new Matser();
    public BufferedImage StreamToImage(String str){
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(str);
        BufferedImage bufferedImage=null;
        try {
            bufferedImage= ImageIO.read(resourceAsStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bufferedImage;

    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);


        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("image/background1.jpg");
        BufferedImage read=null;
        try {
             read= ImageIO.read(resourceAsStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Image image = new ImageIcon(read).getImage();
        g.drawImage(image, 0, 0, 1024, 680, null);
        if(time>0) {
            if(bloodMan>0&&bloodMaster>0){
                BufferedImage image11 = StreamToImage("image/bloodliang.png");


                Image image1 = new ImageIcon(image11).getImage();

                g.drawImage(image1, 10, 20, null);
                g.drawImage(image1, 510, 20, null);


                drawSuperMan(g);
                drawMaster(g);
                drawblood(g);


                g.setColor(Color.BLUE);
                Font font1 = new Font("黑体", Font.BOLD, 20);
                g.setFont(font1);
                g.fillRect(44, 38, bloodMan, 20);

                g.setColor(Color.RED);
                Font font = new Font("黑体", Font.BOLD, 20);
                g.setFont(font);
                g.fillRect(550, 38, bloodMaster, 20);

                g.setColor(Color.CYAN);
                Font font2 = new Font("黑体", Font.BOLD, 20);
                g.setFont(font2);
                g.drawString("" + time / 10, 502, 100);

            }
            else if(bloodMan<=0&&bloodMaster>0)
            {
                g.setColor(Color.WHITE);
                Font font3 = new Font("黑体", Font.BOLD, 80);
                g.setFont(font3);
                g.drawString(" The red side ",200,300);
                g.drawString("won  the  game.",200,400);

                try {
                    if(AsStream == null)
                    {

                    }
                    else {


                        playmusic(AsStream);
                        AsStream=null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
            else if(bloodMaster<=0&&bloodMan>0)
            {
                g.setColor(Color.WHITE);
                Font font3 = new Font("黑体", Font.BOLD, 80);
                g.setFont(font3);
                g.drawString(" The blue side ",200,300);
                g.drawString("won   the   game.",200,400);

                try {
                    if(AsStream1 == null)
                    {

                    }
                    else {


                        playmusic(AsStream1);
                        AsStream1=null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }


        }
        else
        {
            if(bloodMaster>bloodMan)
            {
                g.setColor(Color.WHITE);
                Font font3 = new Font("黑体", Font.BOLD, 80);
                g.setFont(font3);
                g.drawString(" The red side ",200,300);
                g.drawString("won  the  game.",200,400);



                try {
                    if(AsStream == null)
                    {

                    }
                    else {


                        playmusic(AsStream);
                        AsStream=null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            else{
                g.setColor(Color.WHITE);
                Font font3 = new Font("黑体", Font.BOLD, 80);
                g.setFont(font3);
                g.drawString(" The blue    side ",200,300);
                g.drawString("won  the  game.",200,400);

                try {
                    if(AsStream1 == null)
                    {

                    }
                    else {


                        playmusic(AsStream1);
                        AsStream1=null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

        }

        time--;

    }

    public void drawblood(Graphics g)
    {

        if (path ==null) {


        }
        else
        {
            BufferedImage image11 = StreamToImage(path);
            Image image = new ImageIcon(image11).getImage();
            g.drawImage(image, x, y, null);

        }



    }

    private void drawMaster(Graphics g) {
        matser.drawMe(g);
    }

    private void drawSuperMan(Graphics g)
    {

        superMan.drawMe(g);

    }
    public void playmusic(InputStream inputStream) throws Exception{
//        BufferedInputStream bufferedInputStream=new BufferedInputStream(inputStream);
        Player player=new Player(inputStream);
        player.play();


    }

    public void manmove(int keyCode) {
        switch (keyCode){
            case KeyEvent.VK_A:
                superMan.setPose("left");
                break;
            case KeyEvent.VK_D:
                superMan.setPose("right");
                break;
            case KeyEvent.VK_J:
                if(superMan.getPose().equals("foot"))
                {

                }else{

                    superMan.setPose("hand");


                    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/handhit.wav");
                    sound(resourceAsStream);

                }
            case KeyEvent.VK_K:
                if(superMan.getPose().equals("foot")||superMan.getPose().equals("hand"))
                {

                }else{
                    superMan.setPose("defense");
                }
                break;
            case KeyEvent.VK_L:
                if(superMan.getPose().equals("hand"))
                {

                }else{
                    superMan.setPose("foot");


                    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/footman.wav");
                    sound(resourceAsStream);
                }


                break;


        }
    }
    public void mastermove(int keyCode) {
        switch (keyCode){
            case KeyEvent.VK_RIGHT:
                matser.setPose("right");
                break;
            case KeyEvent.VK_LEFT:
                matser.setPose("left");
                break;
            case KeyEvent.VK_NUMPAD1:
                if(matser.getPose().equals("hand"))
                {

                }else{
                    matser.setPose("foot");
                    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/footmaster.wav");
                    sound(resourceAsStream);
                }


                break;
            case KeyEvent.VK_NUMPAD3:

                if(matser.getPose().equals("foot"))
                {

                }else{
                    matser.setPose("hand");
                    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/hithand.wav");
                    sound(resourceAsStream);
                }
                break;
            case KeyEvent.VK_NUMPAD2:
                if(matser.getPose().equals("foot")||matser.getPose().equals("hand"))
                {

                }else{
                    matser.setPose("defense");
                }

                break;


        }
    }
    public void mastercancel(int keyCode) {
        switch(keyCode){
            case KeyEvent.VK_NUMPAD2:
                if(matser.getPose().equals("foot")||matser.getPose().equals("hand"))
                {

                }else{
                    matser.setPose(STATIC);
                }

                break;
        }

    }
    public void action(){
        Timer timer=new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                    hit();
                    repaint();


            }
        },20,100);//delay延迟20毫秒后,period每隔10毫秒执行一次run里面的内容

    }


    public void mancancel(int keyCode) {
        switch(keyCode){
            case KeyEvent.VK_K:
                if(superMan.getPose().equals("foot")||superMan.getPose().equals("hand"))
                {

                }else{
                    superMan.setPose(STATIC);

                }

                break;
        }
    }
    //碰撞检测
    int j=0;
    public void hit(){
        boolean toright1=superMan.toright;
        boolean toright2=matser.toright;

        Image image1;
        String imagePath1 = superMan.getImagePath();
        if(imagePath1==null){
            BufferedImage image11 = StreamToImage("master/toright1.png");
             image1= new ImageIcon(image11).getImage();


        }
        else{
            BufferedImage image11 = StreamToImage(imagePath1);
            image1 = new ImageIcon(image11).getImage();

        }


        int width1 = image1.getWidth(null);
        int height1 = image1.getHeight(null);
        int x1=superMan.getManx();
        int y1=superMan.getMany();
        String pose1 = superMan.getPose();


//        System.out.println(width1);
//        System.out.println(height1);
//        System.out.println(x1);
//        System.out.println(y1);


        String imagePath2 = matser.getImagePath();
        BufferedImage image12 = StreamToImage(imagePath2);
        Image image2 = new ImageIcon(image12).getImage();
        int width2 = image2.getWidth(null);
        int height2 = image2.getHeight(null);
        int x2=matser.getManx();
        int y2=matser.getMany();
        String pose2 = matser.getPose();
//        man的拳 master的静态
        if(pose1.equals("hand")&&pose2.equals("static"))
        {
           if(toright1)
           {
               if(x1+width1>x2&&x1+width1<x2+width2&&y1+height1/3>y2&&y1+height1/3<y2+height2)
               {

                   j++;

                   x=x1+width1;
                   y=y1+height1/5;
                   path="image/blood1.png";
                   InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/afterhit1.wav");
                   sound(resourceAsStream);
                   bloodMaster-=10;
                   x2+=5;
                   matser.setManx(x2);
                   if(j>5)
                   {
                       j=0;
                   }

               }
               else{
                   path=null;

               }

           }
           else
           {
               if(x1>x2&&x1<x2+width2&&y1+height1/3>y2&&y1+height1/3<y2+height2)
               {

                   j++;

                   x=x1;
                   y=y1+height1/5;
                   path= "image/blood1.png";


                   InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/afterhit1.wav");
                   sound(resourceAsStream);
                   x2-=5;
                   matser.setManx(x2);
                   bloodMaster-=10;
                   if(j>5)
                   {
                       j=0;
                   }

               }
               else{
                   path=null;

               }

           }




        }
//        man的脚 master的静态
        else if(pose1.equals("foot")&&pose2.equals("static")){


            if(toright1){
                if(x1+width1>x2&&x1+width1<x2+width2&&y1+height1/3>y2&&y1+height1/3<y2+height2) {
                    x = x1 + width1;
                    y = y1 + height1 *3/ 5;
                    path = "image/blood1.png";


                    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/afterhit1.wav");
                    sound(resourceAsStream);
                    x2+=5;
                    matser.setManx(x2);
                    bloodMaster -= 8;
                }
                else{
                    path=null;
                }

            }else{
                if(x1>x2&&x1<x2+width2&&y1+height1/3>y2&&y1+height1/3<y2+height2) {
                    x = x1;
                    y = y1 + height1 *3/ 5;
                    path = "image/blood1.png";

                    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/afterhit1.wav");
                    sound(resourceAsStream);
                    x2-=5;
                    matser.setManx(x2);
                    bloodMaster -= 8;
                }
                else{
                    path=null;
                }

            }



        }
//          master的拳 man的静态
        else if(pose2.equals("hand")&&pose1.equals("static"))
        {
            if(toright2){
                if(x2+width2>x1&&x2+width2<x1+width1&&y1+height1/3>y2&&y1+height1/3<y2+height2)
                {
                    x = x2+width2;
                    y = y2 + height1 / 5;
                    path = "image/blood1.png";


                    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/afterhit.wav");
                    sound(resourceAsStream);
                    bloodMan -= 10;
                    x1+=3;
                    superMan.setManx(x1);
                }
                else
                {
                    path=null;
                }




            }
            else {
                if(x2>x1&&x2<x1+width1&&y1+height1/3>y2&&y1+height1/3<y2+height2)
                {
                    x = x2;
                    y = y2 + height1 / 5;
                    path = "image/blood1.png";


                    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/afterhit2.wav");
                    sound(resourceAsStream);
                    bloodMan -= 10;
                    x1-=3;
                    superMan.setManx(x1);
                }
                else
                {
                    path=null;
                }

            }




        }


        else if(pose1.equals("static")&&pose2.equals("foot")){
            if(toright2)
            {
                if(x2+width2>x1&&x2+width2<x1+width1&&y1+height1/3>y2&&y1+height1/3<y2+height2)
                {
                    j++;

                    x=x2+width2;
                    y=y2+height1*3/5;
                    path="image/blood1.png";

                    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/afterhit.wav");
                    sound(resourceAsStream);
                    bloodMan-=10;
                    x1+=5;
                    superMan.setManx(x1);
                    if(j>5)
                    {
                        j=0;
                    }


                }
                else{
                    path=null;
                }

            }
            else{
                if(x2>x1&&x2<x1+width1&&y1+height1/3>y2&&y1+height1/3<y2+height2)
                {
                    j++;

                    x=x2;
                    y=y2+height1*3/5;
                    path="image/blood1.png";
                    InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("music/afterhit.wav");
                    sound(resourceAsStream);
                    bloodMan-=10;
                    x1-=5;
                    superMan.setManx(x1);
                    if(j>5)
                    {
                        j=0;
                    }


                }
                else{
                    path=null;
                }

            }




        }
        else{
            path=null;

        }





    }
    public void sound(InputStream inputStream)
    {
        try {


            AudioStream as=new
                    AudioStream(inputStream);
            AudioPlayer.player.start(as);
        }catch(Exception e)
        {
            e.printStackTrace();
        }

    }

    public void sound(String str)
    {
        try {
            FileInputStream in = new FileInputStream(str);
            AudioStream as=new
                    AudioStream(in);
            AudioPlayer.player.start(as);
        }catch(Exception e)
        {
            e.printStackTrace();
        }

    }

    public void restart(int keyCode) {
        if(time<=0||bloodMan<=0||bloodMaster<=0)
        switch(keyCode){
            case KeyEvent.VK_SHIFT:
                time=600;
                bloodMan=430;
                bloodMaster=413;


        }
    }
}


总结

以上是这款对打游戏的初始构建,后续的博文将完成剩下的部分


原文地址:https://blog.csdn.net/qq_43646281/article/details/137723474

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!