gpt4 book ai didi

Java Swing 接口(interface)问题

转载 作者:行者123 更新时间:2023-11-30 08:10:50 25 4
gpt4 key购买 nike

这是我遇到过的最奇怪的错误。每当我启动我的程序时,大约有 2 次中有 1 次成功创建 gui 并弹出窗口。在 2 次中的其他 1 次中,我没有获得任何图形用户界面,也没有任何错误,并且所有代码的执行顺序与成功创建图形用户界面时的顺序相同。

是什么导致了这个错误?我该如何解决这个问题?我很无知..

View 类:

    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");

}
}

创建 View 的类:

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);
}
}
}

关于Java Swing 接口(interface)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31486269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com