使用按钮启动游戏时看不见游戏

问题描述 投票:0回答:1

我是一名学习java的学生,目前正在制作一个游戏。我遇到了一个问题,如果我使用没有 GUI 元素的代码,它可以很好地工作,但是如果我使用相同的方法,唯一的区别是按下按钮时使用它,则负责显示游戏的框架是不可见的.

我可能没有解释清楚,所以我提供了一些代码:这是按预期工作的代码

public class Main {
public static void main(String[] args) {
    initGame();
}
public static void initGame(){
    Game g=new Game();
    try {
       //uses a txt to add players to the game
        g.load();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
    try {
       
        g.play();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}
}

这是应该制作游戏的 GUI 的简化版本,但游戏的框架似乎是空的:

public class Main {
public static void main(String[] args) {
    JFrame frame=new JFrame("Verfarkas");
    JPanel panel=new JPanel();
    JButton button=new JButton();
    button.setPreferredSize(new Dimension(200, 50));
    button.addActionListener(e -> initGame());
    panel.add(button);
    frame.add(panel);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setExtendedState(Frame.MAXIMIZED_BOTH);
    frame.setVisible(true);
}
public static void initGame(){
    Game g=new Game();
    try {
        g.load();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
    try {
      //creates a new frame (i know i already have a frame but this is //a simplified version where i try to fix the problem) and lets players //make their moves
        g.play();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}
}

任何帮助将不胜感激!对于任何语法错误,我深感抱歉,我不是以英语为母语的人。如果需要,我可以提供更多我的代码。

我怀疑解决方案在于使用 SwingUtilities.invokeLater() 但我的知识非常有限。

java swing
1个回答
0
投票

你的摆动窗口没有任何问题 - 我只是尝试并得到了一个带有按钮的最大化窗口。单击它时,会调用 initGame() 方法。

import java.awt.Dimension;
import java.awt.Frame;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class SOTest {
    public static void main(String[] args) {
        JFrame frame=new JFrame("Verfarkas");
        JPanel panel=new JPanel();
        JButton button=new JButton();
        button.setPreferredSize(new Dimension(200, 50));
        button.addActionListener(e -> initGame());
        panel.add(button);
        frame.add(panel);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setExtendedState(Frame.MAXIMIZED_BOTH);
        frame.setVisible(true);
    }

    public static void initGame(){
        System.out.println("initGame");
        new Thread()
    }
}

由于我刚刚删除了您的游戏代码,该代码显然正在阻止某些事情发生。请注意,按钮的 ActionListener 是在事件调度线程上调用的 - 这是唯一一个负责保持 UI 最新的线程。

如果您现在通过在其上运行游戏来阻止该线程 (

g.play()
),它就无法再负责可视化下一帧。因此,您需要生成一个新线程来初始化并运行您的游戏。

因此该方法应如下所示:

public static void initGame(){
    new Thread(() -> {
        System.out.println("initGame");
        ...
    }).start();
}
© www.soinside.com 2019 - 2024. All rights reserved.