当前位置: 代码迷 >> java >> Java Swing接口问题
  详细解决方案

Java Swing接口问题

热度:102   发布时间:2023-07-31 11:30:56.0

这是我遇到过的最奇怪的错误。 每当我启动程序时,大约2次中的1次,GUI就会成功创建并弹出。 在另外2次中的1次中,我没有gui,也没有错误,并且所有代码均以与成功创建gui时相同的顺序执行。

是什么导致此错误? 我该如何解决呢? 我一无所有

视图类:

    package view;

import controller.GameController;
import lombok.Data;
import model.GameModel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

    @Data public class View extends JFrame {

        GameInterface gameInterface = new GameInterface();
        MainMenuScreen menuScreen = new MainMenuScreen();

        public View() {
            super("View");
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            displayMenuScreen();
            setVisible(true);
        }

        public void displayMenuScreen(){
            menuScreen.getSTARTTHEGAMEButton().addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    GameModel.getInstance().newGame();
                    displayGameInterface();
                    GameController.startGame();
                }
            });
            setContentPane(menuScreen.getContentPane());
        }

        public void displayGameInterface(){
            setContentPane(gameInterface.getContentPane());
        }
    }

主菜单类:

package view;
import lombok.Data;
import javax.swing.*;

@Data public class MainMenuScreen extends JFrame{
    private JButton STARTTHEGAMEButton;
    private JPanel rootPanelMainMenu;
    private JTextPane crazyBananaRepublicTycoonTextPane;

    public MainMenuScreen() {
        super("MY GAME'S NAME");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setContentPane(rootPanelMainMenu);
        System.out.println("HEYHEY3");

    }
}

创建视图的类:

import model.GameModel;
import model.GameModelObserver;
import view.View;

public class CrazyBananaRepublicTycoon {

        public static final void main(String args[]){
            View view = new View();
            view.setVisible(true);
            GameModelObserver gameModelObserver = new GameModelObserver(view.getGameInterface());
            GameModel.getInstance().addObserver(gameModelObserver);
            GameModel.getInstance().setGameModelObserver(gameModelObserver);
        }
    }

您没有正确使用事件调度线程...

您只能通过EDT与大多数Swing / AWT对象进行交互。

更改您的主要方法:

public static final void main(String args[])  {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            View view = new View();
            view.setVisible(true);
            GameModelObserver gameModelObserver = new GameModelObserver(view.getGameInterface());
            GameModel.getInstance().addObserver(gameModelObserver);
            GameModel.getInstance().setGameModelObserver(gameModelObserver);
        }
    }
}
  相关解决方案