Java 在actionListener内创建GUI时不显示按钮/标签

Java 在actionListener内创建GUI时不显示按钮/标签,java,swing,user-interface,render,actionlistener,Java,Swing,User Interface,Render,Actionlistener,============== 我正在创建一个由“主菜单”GUI和“游戏中”GUI(用于渲染图形)组成的小型2D游戏 主菜单自然有一个“开始”按钮来创建游戏世界和游戏中的GUI。如果独立运行所有组件,则它们都可以正常工作,但如果在“开始”按钮上的操作侦听器中调用“actionPerformed”,则游戏中的GUI不会正确呈现所有按钮/标签/滚动窗格,并且不会应用默认的关闭操作 图像: 在左侧,不渲染按钮。在右边,他们是 生成左/右图像的代码之间的差异: -对于左图像- -为正确的形象- 请注意,当

==============

我正在创建一个由“主菜单”GUI和“游戏中”GUI(用于渲染图形)组成的小型2D游戏

主菜单自然有一个“开始”按钮来创建游戏世界和游戏中的GUI。如果独立运行所有组件,则它们都可以正常工作,但如果在“开始”按钮上的操作侦听器中调用“actionPerformed”,则游戏中的GUI不会正确呈现所有按钮/标签/滚动窗格,并且不会应用默认的关闭操作

图像

在左侧,不渲染按钮。在右边,他们是

生成左/右图像的代码之间的差异:

-对于左图像- -为正确的形象- 请注意,当按钮未显示时,您无法通过单击右上角的“X”关闭窗口(尽管正在执行setDefaultCloseOperation行)。调整窗口大小会导致重新绘制“小故障”(imgur.com/bOpCzGC)。单击/悬停在按钮上方时,按钮不会重新绘制或作出反应

  • 如果我在世界级中放置一个main方法,并在没有任何形式的主菜单GUI的情况下运行它,那么它就可以正常工作
  • 如果我通过调用World构造函数(调用游戏中的GUI构造函数)绕过主菜单,在它有机会被显示之前(如“FOR RIGHT IMAGE”),它会生成上面的正确图像
  • 似乎游戏GUI中的所有代码行都已执行
  • 当按钮未显示时,游戏实际上会运行。但您无法控制滚动窗格、按钮或标签
我看不出是什么导致了这个问题,并试图找到解决办法。有人能帮我吗?非常感谢

亲切问候,

-本

所有代码 下面是导致问题的所有代码。我只包括了构造函数(现在),因为即使只是运行它们也会导致问题

模拟GUI(也称为游戏GUI)
import javax.swing.*;
导入java.awt.*;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.image.*;
导入javax.imageio.imageio;
导入java.io.*;
导入java.util.ArrayList;
导入java.util.Random;
导入java.util.HashMap;
公共类模拟GUI扩展JFrame{
Pos[][]位置;//包含有关单元格的所有信息的二维位置数组
int imageXSize=25;
int-imageYSize=27;
int-imageXOffset=21;
int rowOffsetValue=(imageXOffset/2);
int-imageYOffset=16;
int curRound=0;
布尔isRendering=true;
公共布尔值isActive=true;
int-antTrackerID=50;
JFrame-simGUIFrame=this;
//公共静态void main(字符串[]args)
//  {
//setProperty(“sun.java2d.opengl”,“True”);
//MapParser mp=新的MapParser();
//SimulationGUI=newSimulationGUI(“一些文本”,mp.parseMap(“1.world”);
//gui.setUpWorld();
//  }
//GUI元素
JPanel地面帆布;
屏幕外的缓冲图像;
缓冲图像背景;
图形2d-crgfx;
图2d-bckGrdGfx;
JScrollPane滚动窗格;
//Graphics2D g2d=新的Graphics2D();
//一堆蚂蚁和食物的图像
BuffereImage antBLK_S;
BuffereImage antBLK_SE;
buffereImage antBLK_E;
BuffereImage antBLK_NE;
BuffereImage Antblkn;
BuffereImage antBLK_NW;
BuffereImage antBLK_W;
BuffereImage antBLK_SW;
BuffereImage Antblkfs;
BuffereImage antBLKF_SE;
BuffereImage antBLKF_E;
BuffereImage antBLKF_NE;
BuffereImage antBLKF_N;
BuffereImage antBLKF_西北;
BuffereImage antBLKF_W;
BuffereImage antBLKF_SW;
缓冲图像的反方向;
缓冲图像反义;
缓冲图像有槽;
缓冲图像和图像;
缓冲图像的反方向;
缓冲图像向西北方向倾斜;
缓冲图像的反方向;
缓冲图像反方向_SW;
缓冲图像的反时限;
缓冲图像反时限;
缓冲区图像反时限;
缓冲图像反时限;
缓冲区图像反时限;
BuffereImage Anteredf_NW;
缓冲区图像反时限;
缓冲区图像Anteredf_SW;
缓冲图像食物_5;
缓冲图像食品4;
缓冲图像食物_3;
缓冲图像食品2;
缓冲图像食物_1;
缓冲图像细胞;
ImageIcon boxChecked=新的ImageIcon(“Images/Check Button checked.png”);
ImageIcon boxUnChecked=新图像图标(“Images/Check Button unchecked.png”);
ImageIcon playButton=新的ImageIcon(“Images/playButton.png”);
ImageIcon pausedButton=新的ImageIcon(“Images/pausedButton.png”);
ImageIcon restartIcon=newImageIcon(“Images/Restart Icon.png”);
ImageIcon quitIcon=新建ImageIcon(“Images/Quit Icon.png”);
ImageIcon foodIcon=新的ImageIcon(“Images/foodIcon.png”);
//GUI中使用的变量
JProgressBar progressBar;
世界;
JLabel圆形计数器;
字符串roundNum;
JLabel红细胞计数;
JLabel blkCount;
JLabel foodCount;
JButton renderPause;
JLabel-redScore;
JLabel-blkScore;
JLabel-antTrackerLabel;
JTextField-antTrackerIDBox;
//世界级使用的参数
HashMap antMap=新的HashMap();
ArrayList foodPosArray=新的ArrayList();
公共模拟GUI(字符串标题,Pos[][]位置数组,World w)
{
groundCanvas=newjpanel();
redCount=new JLabel(“红蚂蚁:未选中,JLabel.LEFT”);
blkCount=new JLabel(“黑蚂蚁:左”);
foodCount=new JLabel(“Food:#######”,foodIcon,JLabel.LEFT);
redScore=新的JLabel(“redScore:########”);
blkScore=新的JLabel(“Blk分数:”;
renderPause=新的JButton(“渲染”,复选框);
scrollPane=新的JScrollPane(groundCanvas);
antTrackerLabel=新的JLabel(“Ant ID”);
antTrackerIDBox=新的JTextField(“20”);
this.world=w;
这个职位=
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class BensGUI extends JFrame{

    public BensGUI()
    {
        final JFrame bensGUI = this;
        Container pane = this.getContentPane();
        JPanel mainPanel = new JPanel();
        JButton start = new JButton("Start");
        mainPanel.add(start);

        //This GUI is simplified from the real Main Menu


        start.addActionListener(new ActionListener() { 
              public void actionPerformed(ActionEvent e) { 
                    Player p1 = new Player("player 1", new AntBrainParser().parseBrain("cleverbrain2.brain"));
                    Player p2 = new Player("player 2", new AntBrainParser().parseBrain("horseshoe.brain"));
                    Pos[][] ps = new MapParser().parseMap("5.world"); //The World class creates the in-game GUI inside its constructor
                    World w = new World(p1, p2, ps, 3427);
                  } 
        } );



        pane.add(mainPanel);
        this.pack();
        this.setVisible(true);
    }
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class BensGUI extends JFrame{

    public BensGUI()
    {
        final JFrame bensGUI = this;
        Container pane = this.getContentPane();
        JPanel mainPanel = new JPanel();
        JButton start = new JButton("Start");
        mainPanel.add(start);


        Player p1 = new Player("player 1", new AntBrainParser().parseBrain("cleverbrain2.brain"));
        Player p2 = new Player("player 2", new AntBrainParser().parseBrain("horseshoe.brain"));
        Pos[][] ps = new MapParser().parseMap("5.world");
        World w = new World(p1, p2, ps, 3427); //The World class creates the in-game GUI inside its constructor

        start.addActionListener(new ActionListener() { 
              public void actionPerformed(ActionEvent e) { 

                  } 
        } );

        //This GUI is simplified from the real Main Menu

        pane.add(mainPanel);
        this.pack();
        this.setVisible(true);
    }
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.*;

import javax.imageio.ImageIO;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.HashMap;

public class SimulationGUI extends JFrame{


    Pos[][] position;//2D array of positions which contains all the info about the cells
    int imageXSize = 25;
    int imageYSize = 27;
    int imageXOffset = 21;
    int rowOffsetValue = (imageXOffset/2);
    int imageYOffset = 16;
    int curRound = 0;
    boolean isRendering = true;
    public boolean isActive = true;
    int antTrackerID = 50;

    JFrame simGUIFrame = this;


//  public static void main(String[] args)
//  {
//      System.setProperty("sun.java2d.opengl","True");
//      MapParser mp = new MapParser();
//      SimulationGUI gui = new SimulationGUI("Some text", mp.parseMap("1.world"));
//      gui.setUpWorld();
//  }


    //GUI ELEMENTS
    JPanel groundCanvas;
    BufferedImage offscreen;
    BufferedImage background;
    Graphics2D offScrGfx;
    Graphics2D bckGrdGfx;

    JScrollPane scrollPane;
    //Graphics2D g2d = new Graphics2D();


    //A load of ant and food images
    BufferedImage antBLK_S;
    BufferedImage antBLK_SE;
    BufferedImage antBLK_E;
    BufferedImage antBLK_NE;
    BufferedImage antBLK_N;
    BufferedImage antBLK_NW;
    BufferedImage antBLK_W;
    BufferedImage antBLK_SW; 

    BufferedImage antBLKF_S;
    BufferedImage antBLKF_SE;
    BufferedImage antBLKF_E;
    BufferedImage antBLKF_NE;
    BufferedImage antBLKF_N;
    BufferedImage antBLKF_NW;
    BufferedImage antBLKF_W;
    BufferedImage antBLKF_SW; 


    BufferedImage antRED_S;
    BufferedImage antRED_SE;
    BufferedImage antRED_E;
    BufferedImage antRED_NE;
    BufferedImage antRED_N;
    BufferedImage antRED_NW;
    BufferedImage antRED_W;
    BufferedImage antRED_SW; 

    BufferedImage antREDF_S;
    BufferedImage antREDF_SE;
    BufferedImage antREDF_E;
    BufferedImage antREDF_NE;
    BufferedImage antREDF_N;
    BufferedImage antREDF_NW;
    BufferedImage antREDF_W;
    BufferedImage antREDF_SW; 


    BufferedImage food_5;
    BufferedImage food_4;
    BufferedImage food_3;
    BufferedImage food_2;
    BufferedImage food_1;

    BufferedImage antTrackCell;


    ImageIcon boxChecked = new ImageIcon("Images/Check Button checked.png");
    ImageIcon boxUnChecked = new ImageIcon("Images/Check Button unchecked.png");
    ImageIcon playButton = new ImageIcon("Images/Play Button.png");
    ImageIcon pausedButton = new ImageIcon("Images/Paused Button.png");
    ImageIcon restartIcon = new ImageIcon("Images/Restart Icon.png");
    ImageIcon quitIcon = new ImageIcon("Images/Quit Icon.png");
    ImageIcon foodIcon = new ImageIcon("Images/foodIcon.png");


    //Variables used in GUI
    JProgressBar progressBar;
    World world;
    JLabel roundCounter;
    String roundNum;
    JLabel redCount;
    JLabel blkCount;
    JLabel foodCount;
    JButton renderPause;
    JLabel redScore;
    JLabel blkScore;
    JLabel antTrackerLabel;
    JTextField antTrackerIDBox;





    //Parameters used by the World Class
    HashMap<Integer, Ant> antMap = new HashMap<Integer, Ant>();
    ArrayList<Pos> foodPosArray = new ArrayList<Pos>();



    public SimulationGUI(String title, Pos[][] positionArray, World w)
    {



        groundCanvas = new JPanel();

        redCount = new JLabel("Red Ants:   ######", boxUnChecked, JLabel.LEFT);
        blkCount = new JLabel("Black Ants: ######", boxUnChecked,  JLabel.LEFT);
        foodCount = new JLabel("Food: ######", foodIcon,  JLabel.LEFT);
        redScore = new JLabel("Red Score:  ######");
        blkScore = new JLabel("Blk Score:  ######");
        renderPause = new JButton("Render", boxChecked);
        scrollPane = new JScrollPane(groundCanvas);
        antTrackerLabel = new JLabel("Ant ID");
        antTrackerIDBox = new JTextField("20");

        this.world = w;
        this.position = positionArray;
        this.setTitle("Ant Simulation | "+title);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



        this.setLocation(400, 400);
        this.setVisible(true);
        Container pane = this.getContentPane();


        //Graphics Setup
//      System.setProperty("sun.java2d.opengl","True");

        //Canvas and JScrollPane

        groundCanvas.setPreferredSize(new Dimension(imageXOffset*position.length + 10,imageYOffset*position.length + 10));
        offscreen = (BufferedImage) createImage(imageXOffset*position.length + 10,imageYOffset*position.length + 10);
        background = (BufferedImage) createImage(imageXOffset*position.length + 10,imageYOffset*position.length + 10);
        offScrGfx = (Graphics2D) offscreen.getGraphics();
        bckGrdGfx = (Graphics2D) background.getGraphics();


        scrollPane.add(groundCanvas);
        scrollPane.setPreferredSize(new Dimension(800,450));
        scrollPane.setViewportView(groundCanvas);




        ///////////////////////////


        JPanel topPanel = new JPanel();
        JPanel middlePanel = new JPanel();
        JPanel bottomPanel = new JPanel();
        JPanel bottomMainPanel = new JPanel();
        JPanel topMainPanel = new JPanel();
        JPanel antTracker = new JPanel();

        bottomPanel.setLayout(new BorderLayout());
        topMainPanel.setLayout(new GridLayout(2,3));
        topPanel.setLayout(new BorderLayout());
        antTracker.setLayout(new BorderLayout());

        JButton restartButton = new JButton("Restart", restartIcon);
        final JButton pauseButton = new JButton("Pause", playButton);
        JButton quitButton = new JButton("Quit", quitIcon);
        final JButton speedUp = new JButton("");
        final JButton slowDown = new JButton("");
        speedUp.setIcon(new ImageIcon("Images/speedUp.png"));
        slowDown.setIcon(new ImageIcon("Images/slowDown.png"));

//      progressBar = new JProgressBar(0, w.maxRounds);
//      progressBar.setValue(0);
//      progressBar.setStringPainted(true);


        roundCounter = new JLabel("Round: #######");


        //ACTION LISTENERS////////


        //Action listeners are commented out for now...

        //Add the buttons/bars/labels to their panels


        bottomMainPanel.add(roundCounter);
        bottomMainPanel.add(speedUp);
        bottomMainPanel.add(slowDown);
        bottomMainPanel.add(renderPause);
        bottomMainPanel.add(restartButton);
        bottomMainPanel.add(pauseButton);
        bottomMainPanel.add(quitButton);
        bottomPanel.add(bottomMainPanel, BorderLayout.SOUTH);
        //bottomPanel.add(progressBar, BorderLayout.NORTH);


        JPanel antTrackerContainer = new JPanel();

        antTrackerContainer.add(antTrackerLabel);
        antTrackerContainer.add(antTrackerIDBox);
        antTracker.add(antTrackerContainer, BorderLayout.WEST);


        antTrackerIDBox.setPreferredSize(new Dimension(40, 20));


        topMainPanel.add(redCount);
        topMainPanel.add(redScore);
        topMainPanel.add(foodCount);
        topMainPanel.add(blkCount);
        topMainPanel.add(blkScore);
        topMainPanel.add(antTracker);


        middlePanel.add(scrollPane);



        topPanel.add(topMainPanel, BorderLayout.CENTER);

        pane.add(topPanel, BorderLayout.NORTH);
        pane.add(middlePanel, BorderLayout.CENTER);
        pane.add(bottomPanel, BorderLayout.SOUTH);


        this.pack();



    }
World(Player player1, Player player2, Pos[][] positions, int initialSeed) {
        // initialise variables
        this.player1 = player1;
        this.player2 = player2;
        player1.setColour("red");
        player2.setColour("black");
        this.positions = positions;
        this.foodPositions = new ArrayList<Pos>();
        ants = new HashMap<Integer, Ant>();
        this.initialSeed = initialSeed;

        seed.add(new BigInteger("" + initialSeed)); // initial seed
        for (int i = 1; i < 4; i++) {
            seed.add(seed.get(i - 1).multiply(new BigInteger("22695477"))
                    .add(new BigInteger("1")));
        }

        generateAnts();
        System.out.println(ants.size());
        //In-Game GUI Setup:
        sim = new SimulationGUI("", positions, this);
        sim.setUpWorld();
        sim.pack();
        gameStart();
    }