(Java GUI)JPanel 未显示在 removeAll() 方法后通过方法返回

(Java GUI) JPanel not showing up returning through method after removeAll() method

下面,我正在创建一个 JFrame class(只是重要的部分发布在下面的 class 中)。创建 UserInterface 对象时,一切正常,但激活 eventListener 时除外。本段代码:

getContentPane().removeAll();
getContentPane().add(gameScreen());
getContentPane().validate();
getContentPane().repaint();

似乎没有按预期工作。 removeAll() 方法起作用,但将 gameScreen 方法(returns 面板)添加到 JFrame 不会执行任何操作。知道为什么吗?

public class UserInterface extends JFrame{

public UserInterface(){
    super("idk");
    setName("idk");
    setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBackground(Color.WHITE);
    setResizable(false);
    setLocationRelativeTo(null);
    add(startScreen());
    setVisible(true);
}//UserInterface

private class beginButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        getContentPane().removeAll();
        getContentPane().add(gameScreen());
        getContentPane().validate();
        getContentPane().repaint();
    }
}//beginButtonListener

public JPanel gameScreen(){

    JPanel gamePanel = new JPanel();
    gamePanel.setName("gamePanel");
    gamePanel.setLayout(null);

    JLabel fadeShade = new JLabel();
    fadeShade.setName("fadeShade");
    fadeShade.setBackground(Color.BLUE);
    fadeShade.setBounds(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
    gamePanel.add(fadeShade);
    return gamePanel;
}//gameScreen
}//UserInterface

是的,您的游戏面板可能确实已添加,但您永远不会看到它。您向其中添加一个 JLabel,标签上没有任何文本,并且您设置标签的背景颜色而不使标签不透明。您还使用空布局,这是一件非常危险的事情。

如果这是我的代码,我会

  • 使用 CardLayout 交换组件
  • 避免 null 像瘟疫一样的布局,而是让布局管理员为我完成繁重的布局提升。
  • 确保设置任何需要显示文本的 JLabel 的文本。设置 JLabel 的名称 属性 可能对我帮助不大。