集成两个窗口的Java乒乓游戏

如何解决集成两个窗口的Java乒乓游戏

我刚开始学习编程,为了我的考试项目,我决定制作一个带有菜单的乒乓球游戏。 我目前的主要问题是弄清楚如何从菜单中构建和启动我的游戏。菜单和游戏都可以很好地分开,但我不知道如何整合它们。或者更准确地说,如何从菜单开始乒乓球比赛。

我制作了一个从“菜单”切换到“游戏”的开始按钮。如果我只是插入一些背景颜色,它工作正常。但是,当我尝试切换到“游戏模式”时,开始按钮会冻结。

集成的最佳实践是什么?有 2 种paintcomponent 方法重要吗?任何人都可以帮助新人吗?

感谢所有提示!

这是我的代码和我无法工作的 spil() 方法。

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.sound.midi.Soundbank;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Game extends JPanel {
    
    JFrame frame =new JFrame();
    
    // Paneler objekter
    JPanel panelc= new JPanel();
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    JPanel pNorth = new JPanel();
    JPanel pCenter = new JPanel();

    // Objekter Gamemenu
    CardLayout cl = new CardLayout();
    MovingBall mb=new MovingBall();
    JLabel nTitel = new JLabel();
    JLabel sTekst = new JLabel("--- Må den bedste spiller vinde ---");
    JComboBox<String> cBane = new JComboBox<String>();
    JButton start= new JButton("START");
    JComboBox<String> cP1 = new JComboBox<String>();
    JComboBox<String> cP2 = new JComboBox<String>();
    JTextField cName1 = new JTextField("Navn på spiller 1");
    JTextField cName2 = new JTextField("Navn på spiller 2");
    JLabel pic = new JLabel();
    
    
    Banelistener bl= new Banelistener();
    Banelistener s= new Banelistener();
        
    // Variable Gamemenu
    String filstring = "C:\\Users\\b047222\\Desktop\\DTU - GP\\lava2.jpg"; //bør sættes til null efter program virker
    public static int vinduesbredde = 900;
    public static int vindueshøjde = 500;
    BufferedImage image = null;
    String clnummer = "1";
    
    public static void main(String[] args) {

        
        Game game = new Game();
        
        
        
    }

    public Game() {
        frame.setSize(new Dimension(vinduesbredde,vindueshøjde));
        frame.setTitle("Lava Spillet");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null); // Center the frame
        frame.setVisible(true);
                        
        // Layout
        panelc.setLayout(cl);
        panelc.add(panel1,"1");
        panelc.add(panel2,"2");
        panel1.setLayout(new BorderLayout());
        panel1.add(pNorth,BorderLayout.NORTH);
        panel1.add(pCenter);
        pCenter.setLayout(null);
        panel2.add(mb);
        mb.setFocusable(true);
        mb.addKeyListener(mb);
        cl.show(panelc,clnummer);
        start.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                clnummer="2";
                cl.show(panelc,clnummer);
                spil();
            }               
            
        });
        

        repaint();
                
        // Eventhandlers
        cBane.addActionListener(bl);
        
        // North
        nTitel.setText("LAVA");
        nTitel.setForeground(Color.orange);
        nTitel.setFont(new Font("Verdana",Font.BOLD,24));
        pNorth.setBackground(Color.black);
        pNorth.add(nTitel);

        // Center
        int x1 = 200;
        int x2 = 675;
        int y1 = 100;
        int y2 = 330;
        int y3 = 365;
        int bx = 100;
        int by = 25;

        pCenter.add(cBane);
        cBane.setBackground(Color.orange);
        cBane.setBounds(vinduesbredde / 2 - bx / 2,100,bx,by);
        cBane.addItem("Lavaland");
        cBane.addItem("Enhjørningeland");
        cBane.addItem("Jungle");
        pCenter.add(start);
        start.setBounds(vinduesbredde / 2 - bx / 2,140,by);

        pCenter.add(cName1);
        cName1.setBounds(x1,y2,by);
        cName1.setText("Navn på spiller 1");

        pCenter.add(cP1);
        cP1.setBounds(x1,y3,by);
        cP1.addItem("Elsa");
        cP1.addItem("Vaiana");
        cP1.addItem("Runde Tårn");
        
        pCenter.add(cName2);
        cName2.setBounds(x2,by);
        cP2.addItem("Elsa");
        cP2.addItem("Vaiana");
        cP2.addItem("Runde Tårn");
        pCenter.add(cP2);
        cP2.setBounds(x2,by);
                
        // South
        pCenter.add(sTekst);
        sTekst.setBounds(vinduesbredde / 2 - 80,400,200,by);     
        
        
        frame.add(panelc);
    }
    
    public void spil() {
        
        mb.addKeyListener(mb);
        mb.setFocusable(true);
        cl.show(panelc,"2");
        while (true) {
            mb.move();
            mb.repaint();
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }           
    }
        
    protected void paintComponent(Graphics g) {             
        File fil = new File(filstring);
                try {
                    image = ImageIO.read(fil);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                super.paintComponent(g);
                    g.drawImage(image,vinduesbredde,vindueshøjde,this);
                    g.drawRect(100,50,50);
            }   
    
class Banelistener implements ActionListener {
            @Override
            public void actionPerformed(ActionEvent e) {
                
                //baggrund ved banevalg
                 JComboBox valg = (JComboBox) e.getSource();
                 Object valgt= valg.getSelectedItem();  
                 String land = valgt.toString();
                
                switch (land) {
                case "Lavaland":
                    filstring = "C:\\Users\\b047222\\Desktop\\DTU - GP\\lava2.jpg";
                    break;
                
                case "Enhjørningeland":
                    filstring = "C:\\Users\\b047222\\Desktop\\DTU - GP\\Enhorning.jpg";
                    break;
                    
                case "Jungle":
                    filstring = "C:\\Users\\b047222\\Desktop\\DTU - GP\\Jungle.jpg";
                    break;
                }           
                pNorth.repaint();
        }       
}

}

/////////////////////////////

class MovingBall extends JPanel implements KeyListener{
    
    Bar b1 = new Bar("Adam","Elsa",GameMenu.vindueshøjde/2-40); //bør gøres dynamisk ud fra den enkelte karakter
    Bar b2 = new Bar("Alma","Vaiana",GameMenu.vinduesbredde,GameMenu.vindueshøjde/2-40);
    
    Random ran = new Random();
    int x=1; 
    int y=ran.nextInt(200); //skal laves dynamisk ift. framestørrelse
    int vinkelx= 1;
    Boolean opned= ran.nextBoolean();// gør det muligt at bolden kan starte i anden retning
    int vinkely;
    {if (opned==true) 
        {vinkely =1;} 
    else {vinkely =-1;} }
    int ballradius=25;
    int hastighed=10;
    
    void move () {
        //bounce på bat x-akse
        if (x+vinkelx==b1.x+Bar.figwidth && y+vinkely < b1.y+b1.h && y+vinkely > b1.y) {
            vinkelx=1;}
        if (x+vinkelx==b2.x && b2.y<y+vinkely && b2.y+b2.h>y+vinkely) {
            vinkelx=-1;}
        
        //bounce på bat y-akse
        if (y+vinkely==b1.y+Bar.figheight && x+vinkelx < b1.x+b1.w && x+vinkelx > b1.x) {
            vinkely=1;}
        if (y+vinkely==b1.y && x+vinkelx < b1.x+b1.w && x+vinkelx > b1.x) {
            vinkely=-1;}
        if (y+vinkely==b2.y+Bar.figheight && x+vinkelx < b2.x+b2.w && x+vinkelx > b2.x) {
            vinkely=1;}
        if (y+vinkely==b2.y && x+vinkelx < b2.x+b2.w && x+vinkelx > b2.x) {
            vinkely=-1;}
                    
        //Bevægelse af bold
        if (x+vinkelx < 0) {
            vinkelx=1;      
        } else if (x+vinkelx> getWidth()-ballradius) {
            vinkelx=-1;
        } else if (y+vinkely < 0) {
            vinkely=1;      
        } else if (y+vinkely> getHeight()-ballradius) {
            vinkely=-1;
        }           
        
        //score
        if (x==GameMenu.vinduesbredde) {
            b2.score=b2.score+1;}
        if (x==0) {
            b1.score=b1.score+1;}
        
        x=x+vinkelx;
        y=y+vinkely;
        
    
    }
    
    int scorex1=(int) (GameMenu.vinduesbredde*0.25);
    int scorex2=(int) (GameMenu.vinduesbredde*0.75);
    int scorey=25;
    int scoreb=70;
    int scoreh=50;
    
    String p1vinder=b1.navn.toUpperCase()+" HAR VUNDET!!!";
    String p2vinder=b2.navn.toUpperCase()+" HAR VUNDET!!!";

     protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(b1.image,b1.x,b1.y,b1.w,b1.h,null);
                g.drawImage(b2.image,b2.x,b2.y,b2.w,b2.h,null);
                g.drawLine(GameMenu.vinduesbredde/2,GameMenu.vinduesbredde/2,GameMenu.vindueshøjde);
                g.setColor(Color.GRAY);
                g.fillRect( scorex1,scorey,scoreb,scoreh);
                g.fillRect( scorex2,scoreh);
                g.setColor(Color.ORANGE);
                g.setFont(new Font("Helvetica",25));
                g.drawString(String.valueOf(b1.score),scorex1+scoreb/2-6,scorey+scoreh/2+8);
                g.drawString(String.valueOf(b2.score),scorex2+scoreb/2-6,scorey+scoreh/2+8);
                g.setColor(Color.BLACK);
                g.fillOval(x,y,ballradius,ballradius);
                g.setFont(new Font("Helvetica",50));

                if (b1.score>9) {
                    g.drawString(p1vinder,(int) (GameMenu.vinduesbredde*0.50)-250,(int) (GameMenu.vindueshøjde/2)-5); 
                }
                    else if (b2.score>9) {
                    g.drawString(p2vinder,(int) (GameMenu.vindueshøjde/2)-5);
                    
                    }
            }
    
     public void keyTyped(KeyEvent e) {
            // TODO Auto-generated method stub
        }

    public void keyPressed(KeyEvent e) {
            if (e.getKeyCode()==KeyEvent.VK_W) {
                if (b1.y>0) {
                    b1.y=b1.y-hastighed;
                }
                }
            else if (e.getKeyCode()==KeyEvent.VK_S) {
                    if (b1.y<GameMenu.vindueshøjde) {
                    b1.y=b1.y+hastighed;
                    }
                }
            if (e.getKeyCode()==KeyEvent.VK_UP) {
                if (b2.y>0) {
                    b2.y=b2.y-hastighed;
                    }
                }
                else if (e.getKeyCode()==KeyEvent.VK_DOWN) {
                    if (b2.y<GameMenu.vindueshøjde) {
                    b2.y=b2.y+hastighed;
                    }
                }
                repaint();
        }

        public void keyReleased(KeyEvent e) {
        }
} 
     
class Bar extends JPanel {
    
    String navn="test"; 
    int w;
    int h;
    int x;
    int y;
    String fig;
    BufferedImage image = null;
    int score;

    static int figwidth=80;
    static int figheight=100;
//  static int elsah=120;
//  static int elsap=elsah/2;
//  static int vaianah=120;
//  static int vaianap=vaianah/2;
//  static int rundetaarnh=100;
//  static int rundetaarnp=rundetaarnh/2;
    
    public Bar(String navn,String figur,int x,int y) {
        
        if (figur=="Elsa") {
            this.navn=navn;
            this.w=figwidth;
            this.h=figheight;
            this.x=x;
            this.y=y;
            this.score=0;
            this.fig="C:\\Users\\b047222\\Desktop\\DTU - GP\\elsa.jpg";
        }
        
        else if (figur=="Vaiana") {
            this.navn=navn;
            this.w=figwidth;
            this.h=figheight;
            this.x=x;
            this.y=y;
            this.score=0;
            this.fig="C:\\Users\\b047222\\Desktop\\DTU - GP\\vaiana.jpg";
        }
        
        else if (figur=="Runde Tårn") {
            this.navn=navn;
            this.w=figwidth;
            this.h=figheight;
            this.x=x;
            this.y=y;
            this.score=0;
            this.fig="C:\\Users\\b047222\\Desktop\\DTU - GP\\taarn.jpg";
            }
        
        File fil = new File(fig);
        try {
            image = ImageIO.read(fil);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        }       
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-