从下一个 class 开始向 JFrame 添加组件

Adding components to JFrame from next class

我有问题。我有主要 class

public static void main(String[] args) {
    HomePanel game = new HomePanel();
    game.setVisible(true);
    game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

带游戏的主页面板:

  public HomePanel() {

    setSize(1280, 720);
    setLayout(null);
    setTitle("MILLION");

    bNewGame = new JButton("New Game");
    bNewGame.setFont(new Font("Tahoma", Font.BOLD, 15));
    bNewGame.setBounds(550, 420, 180, 50);
    bNewGame.setToolTipText("Start a new adventure!");
    bNewGame.addActionListener(this);

带有动作侦听器:

  public void actionPerformed(ActionEvent action) {
    source = action.getSource();

    if (source == bNewGame) {
        new Test().setVisible(true);

还有很多其他人。当我启动此 window 时,在单击 "New Game" 之后我想打开组件 - 我的意思是添加按钮和测试 class 的动作侦听器,但我仍想在相同 window,没有打开一个新的(它确实发生了)。

public class Test extends JFrame{
private JButton bCredits;

public Test() {
    setSize(1280, 720);
    setLayout(null);
    setTitle("TEST_TEST");

    bCredits = new JButton("Credits");
    bCredits.setBounds(550, 540, 180, 50);
    add(bCredits);
}

谁能帮帮我?

我的建议是使用名为 GameFrameJFrame 之类的。然后在 gameFrame 中添加 HomePanel。确保 homePanel 扩展 JPanel 或某个容器。如果需要,只需从框架中删除 homePanel 并添加另一个视图。像

remove(homePanel);
add(nextView);

还要确保 nextView 扩展了 JPanel 或某些容器。 使用布局管理器更好地定位