首页 > 解决方案 > 集成两个窗口的Java乒乓球游戏

问题描述

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

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

集成的最佳实践是什么?有两种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, bx, by);

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

        pCenter.add(cP1);
        cP1.setBounds(x1, y3, bx, by);
        cP1.addItem("Elsa");
        cP1.addItem("Vaiana");
        cP1.addItem("Runde Tårn");
        
        pCenter.add(cName2);
        cName2.setBounds(x2, y2, bx, by);
        cP2.addItem("Elsa");
        cP2.addItem("Vaiana");
        cP2.addItem("Runde Tårn");
        pCenter.add(cP2);
        cP2.setBounds(x2, y3, bx, 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,0,0, vinduesbredde, vindueshøjde, this);
                    g.drawRect(100, 50, 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",0,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, 0, GameMenu.vinduesbredde/2, GameMenu.vindueshøjde);
                g.setColor(Color.GRAY);
                g.fillRect( scorex1, scorey, scoreb, scoreh);
                g.fillRect( scorex2, scorey, scoreb, scoreh);
                g.setColor(Color.ORANGE);
                g.setFont(new Font("Helvetica", Font.BOLD, 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", Font.BOLD, 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.vinduesbredde*0.50)-250, (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();
        }
        
        }       
    }

标签: javamethodsstructurecardlayout

解决方案


推荐阅读