You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于继承的小型Java GUI程序无法正常显示问题求助

Java GUI加载异常问题:偶尔显示正常,多数情况无内容

我是Java新手(这是我第一次在校外编写程序),目前遇到GUI无法正常打开的问题。奇怪的是,程序偶尔能正常显示并运行(大概10次里有1次),但大多数情况下JFrame打开后内部没有任何可见内容。

相关代码类

GUI.java

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.border.Border;

public class GUI {
    
    JFrame frame;
    JPanel panel;
    
    public GUI() {
        frame = new JFrame();
        frame.setTitle("Word Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setResizable(false);
        frame.setVisible(true);
        
        panel = new JPanel();
        panel.setBackground(Color.red);
        panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
        panel.setLayout(new GridLayout(1, 0));
    }
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;

public class MainMenu extends GUI implements ActionListener {

    private JButton buttonPlay;
    private JButton buttonStats;
    
    public MainMenu() {
        super();
        
        buttonPlay = new JButton("Play");
        panel.add(buttonPlay);
        buttonPlay.addActionListener(this);
        buttonStats = new JButton("View Leaderboards");
        panel.add(buttonStats);
        buttonStats.addActionListener(this);
        
        frame.add(panel, BorderLayout.CENTER);
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        new SelectLevel(e.getSource() == buttonPlay);
        frame.dispose();
    }

    public static void main(String[] args) {
        new MainMenu();
    }
}

SelectLevel.java

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;

public class SelectLevel extends GUI implements ActionListener {

    
    public SelectLevel(boolean play) {
        super();
        
        for(int i = 1; i <= 3; i++) {
            JButton button = new JButton("Level " + i);
            panel.add(button);
            button.addActionListener(this); 
        }
        
        frame.add(panel, BorderLayout.CENTER);
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        new Game(e.getActionCommand().charAt(6));
        frame.dispose();
    }

    public static void main(String[] args) {
        new MainMenu();
    }
}

界面截图

正常显示界面

  • 主菜单界面:正常显示的主菜单界面
  • 选关界面:正常显示的选关界面

异常显示界面

通常出现的异常界面:JFrame无内容

内容的提问来源于stack exchange,提问作者Piter De Vries

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 02:58:09