将 JPanel 对象添加到单独的 JPanel 中

Adding JPanel Object into a separate JPanel

我正在制作一个菜单,我想尽可能使其成为面向对象的,因此我为菜单 JPanel 对象创建了一个单独的 class。问题是它不想将它添加到我的主 JPanel 中。我做错了什么,我该如何解决?

主要Class:

package Whosebug;
import java.awt.CardLayout;
import javax.swing.*;

public class Main {

    private JFrame frame = new JFrame();
    private JPanel MainPanel = new JPanel();
    private CardLayout cl = new CardLayout();
    private GamePanel gp = new GamePanel();

    public Main(){
        frame.setLocation(100, 100);
        frame.setSize(1200, 700);
        frame.setTitle("Rain | Pre-Alpha");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        MainPanel.setLayout(cl);

        MainPanel.add(gp, "1");

        frame.add(MainPanel);

        cl.show(MainPanel, "1");

        frame.setVisible(true);
    }

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

游戏面板Class:

package Whosebug;
import java.awt.Color;
import javax.swing.JPanel;

public class GamePanel {
    private JPanel GamePanel = new JPanel();

    public GamePanel(){
        GamePanel.setBackground(Color.green);
    }
}

您无法将 class 添加到您的 JFrame,JFrame 接受 Component :

public Component add(Component comp, int index)

所以你有很多方法可以解决你的问题:

选项 1

改为扩展 JPanel :

public class GamePanel extends JPanel {

    public GamePanel() {
        super.setBackground(Color.green);
    }
}

选项 2

您可以使用 getter 和 setter :

public class GamePanel {

    private JPanel GamePanel = new JPanel();

    public JPanel getGamePanel() {
        return GamePanel;
    }

    public void setGamePanel(JPanel GamePanel) {
        this.GamePanel = GamePanel;
    }

    public GamePanel() {
        GamePanel.setBackground(Color.green);
    }

}

您可以像这样添加 JPanel :

MainPanel.add(gp.getGamePanel(), "1");