简体   繁体   English

游戏的主菜单

[英]Main menu for a game

I'm a beginner trying to create a game. 我是一个尝试创造游戏的初学者。 The game is empty, I didn't start to write it. 游戏是空的,我没有开始写它。

My problem: when I click in the start button I want to start the game in the same frame, but with this code when I'll click on start the program opens another frame with the menu, and in the original frame will delete the panel. 我的问题:当我点击开始按钮时,我想在相同的框架中启动游戏,但是当我点击开始时,使用此代码打开程序打开另一个框架,并在原始框架中删除面板。

How can I do this simple menu? 我该怎么做这个简单的菜单?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import panelimage.Image;

public class Project0 extends JFrame{
private static final long serialVersionUID = 1L;
private Game JPanelGame;
private Image MainMenu = new Image(new File("src/img/menu_background.jpg"));
JButton start = new JButton("START GAME"), exit = new JButton ("LEAVE GAME");

public Project0() {

    super();

    initFrame();
    initMenu();

    this.addKeyListener(new KeyAdapter() {

        public void keyPressed(KeyEvent evt) {
            JPanelGame.keyPressed(evt);
        }

        public void keyReleased(KeyEvent evt) {
            JPanelGame.keyReleased(evt);
        }            
    });

}


private void initFrame() {

    setResizable(false);
    setBounds(new Rectangle(400, 400, 600, 400));
    MainMenu.setLayout(new BorderLayout()); 
}


private void initMenu() {

    initButtons();

    MainMenu.setLayout(null);       
    MainMenu.add(start);
    MainMenu.add(exit);

    add(MainMenu);      
    setContentPane(MainMenu);

    setTitle("Project0");

}

private void initButtons() {

    start.addActionListener(new ActionListener() {  

        public void actionPerformed(ActionEvent e){

            JPanelGame = new Game();

            remove(MainMenu);

            add(JPanelGame, BorderLayout.CENTER);
            setContentPane(JPanelGame);

            invalidate(); validate();

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    Project0 Game = new Project0();
                    Game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    Game.setVisible(true);
                }
            });
        }
    });      

    start.setLocation(225,100);
    start.setSize(150,50);

    exit.addActionListener(new ActionListener() {   

        public void actionPerformed(ActionEvent e){

            System.exit(0);
        }
    });

    exit.setLocation(225,200);
    exit.setSize(150,50);       

}


public static void main(String[] args) {    
    Project0 Game = new Project0();
    Game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Game.setVisible(true);

}

} }

and this frame will start 这个框架将开始

import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;

import java.io.File;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

import highscores.*;


public class Game extends JPanel implements Runnable {

private static final long serialVersionUID = 1L;    

Thread game;
BufferedImage background;
HighscoreManager scores = new HighscoreManager();

public Game(){

    super(true);
    try{
        background = ImageIO.read(new File(""));
    }catch(Exception e) {}


    game=new Thread(this);
    game.start();
}

public void paintComponent(Graphics graphic2d){

    setOpaque(false);       
    super.paintComponent(graphic2d);      

    graphic2d.drawImage(background, 0, 0, null);
}   

public void keyPressed(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {

    }

    if (key == KeyEvent.VK_RIGHT) {

    }

    if (key == KeyEvent.VK_UP) {

    }

    if (key == KeyEvent.VK_DOWN) {

    }

    if (key == KeyEvent.VK_A) {

    }

    if (key == KeyEvent.VK_D) {

    }

    if (key == KeyEvent.VK_W) {

    }

    if (key == KeyEvent.VK_S) {

    }
}

public void keyReleased(KeyEvent e) {

    int key = e.getKeyCode();

    if (key == KeyEvent.VK_LEFT) {

    }

    if (key == KeyEvent.VK_RIGHT) {

    }

    if (key == KeyEvent.VK_UP) {

    }

    if (key == KeyEvent.VK_DOWN) {

    }

    if (key == KeyEvent.VK_A) {

    }

    if (key == KeyEvent.VK_D) {

    }

    if (key == KeyEvent.VK_W) {

    }

    if (key == KeyEvent.VK_S) {

    }
}


public void run(){

        try {Thread.sleep(50);}catch(InterruptedException ex){}     
}

} }

I see two options, depending on your needs. 根据您的需要,我会看到两种选择。 Either you just remove all components from the frame and add the new contents. 您可以从框架中删除所有组件并添加新内容。 But by doing so, you loose your 'menu-frame'. 但通过这样做,你失去了'菜单框架'。 The other option (and IMO the best of the two) is to opt for a CardLayout , where one card is your menu and the other your game. 另一种选择(以及两者中最好的IMO)是选择CardLayout ,其中一张卡是您的菜单,另一张是您的游戏。 The 'start' button would then simply switch from the 'menu-card' to the 'game-card' (and if needed start the game). 然后,“开始”按钮将简单地从“菜单卡”切换到“游戏卡”(如果需要,则启动游戏)。 In your game, you can have a button/key/... which does the inverse (switching from the game card to the menu card) 在你的游戏中,你可以有一个按钮/键/ ...反向(从游戏卡切换到菜单卡)

I was going through your code but I gave up (certainly since @orzechowskid already pointed out what you need to adjust). 我正在阅读你的代码,但我放弃了(当然,因为@orzechowskid已经指出了你需要调整的内容)。 A few tips in case you are going to post more code on this site: 一些提示,以防您要在此网站上发布更多代码:

  1. Read the SSCCE.org website and try to post code as described there 阅读SSCCE.org网站并尝试按照其中的描述发布代码
  2. Follow the Java naming conventions (eg classes start with an uppercase letter, variables with a lowercase letter) 遵循Java命名约定 (例如,类以大写字母开头,变量使用小写字母)
  3. Do not give your own classes the same names as standard JDK classes. 不要为自己的类提供与标准JDK类相同的名称。 Makes it very hard for someone not familiar with your code (but probably rather familiar with the JDK classes) to read the code. 对于不熟悉您的代码(但可能比较熟悉JDK类)的人来说,阅读代码非常困难。 Eg it took me some time before I realized you have your own panelimage.Image class which has nothing to do with the java.awt.Image class 我花了一些时间才意识到你有自己的panelimage.Image类与java.awt.Image类无关

And then a few Swing related tips based on what I saw of your code: 然后根据我看到的代码,提供一些与Swing相关的技巧:

  1. Learn how to use LayoutManager s and get rid of the null layouts. 学习如何使用LayoutManager并摆脱null布局。 The Visual guide to layout managers might be a good starting point 布局管理器可视化指南可能是一个很好的起点
  2. Swing is designed to work with KeyBindings and not with KeyListeners. Swing旨在与KeyBindings一起使用,而不是与KeyListeners一起使用。 See the tutorial 请参阅教程
  3. Be careful with the Thread.sleep usage and running multiple Thread s in combination with a Swing UI. 注意Thread.sleep用法,并结合Swing UI运行多个Thread Make sure you are aware of the Swing threading rules 确保您了解Swing线程规则

when you call SwingUtilities.invokeLater() inside your button's action listener, you're creating a second Project0 object. 当您在按钮的动作侦听器中调用SwingUtilities.invokeLater() ,您将创建第二个Project0对象。 And whenever you create a Project0 , you get a JFrame drawn on screen with a main menu inside of it. 每当你创建一个Project0 ,你会在屏幕上绘制一个JFrame,里面有一个主菜单。 Remove the call to SwingUtilities.invokeLater() and you should be left with a single frame. 删除对SwingUtilities.invokeLater()的调用,你应该留下一个帧。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过Java游戏时返回主菜单 - Return to main menu when game over java Java,使用javaFX作为主菜单,然后切换到游戏本身的JFrame - Java, Using javaFX for the main menu then switching over to JFrame for the game itself 有没有办法在我的Java游戏主菜单中放置视频 - Is there a way of placing a video in my Java game main menu 如何将主菜单连接到我的游戏? - How can i connect the main menu into my game? 在我的 Java 游戏中实现主菜单时使用 createBufferStrategy(int) 生成错误 - Implementing a main menu in my Java game is generating an error with the createBufferStrategy(int) 如何让我的主菜单按钮在我的游戏中工作 - How to make my Main Menu buttons to work in my Game 我的世界自定义启动器,如何跳过主菜单直接进入游戏世界 - minecraft custom launcher, how to skip main menu and go directly into game world LibGDX:如何从主游戏屏幕重复显示/隐藏叠加弹出菜单 - LibGDX: How to show/hide an overlay popup menu from the main game screen repetitively 在一堂课MyGdxGame中编写了整个游戏。 我如何主菜单? libgdx - Wrote the whole game in one class MyGdxGame. How do i mae the main menu? libgdx 如何在我的主游戏屏幕上添加纸牌布局格式,以便在单击按钮时将其从主菜单屏幕更改为我的游戏屏幕代码 - How to add a cardlayout format to my main game screen so that when I click a button it changes from Main Menu screen into my Game Screen Code Provided
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM