我正在处理一个菜单,我希望尽可能使它成为面向对象,所以我为菜单JPanel对象创建了一个单独的类。问题是它不想将它添加到我的主JPanel。我做错了什么,应该如何解决?
主要类别:
package StackOverflow;
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();
}
}
GamePanel类:
package StackOverflow;
import java.awt.Color;
import javax.swing.JPanel;
public class GamePanel {
private JPanel GamePanel = new JPanel();
public GamePanel(){
GamePanel.setBackground(Color.green);
}
}
答案 0 :(得分:1)
您无法向JFrame
添加课程,JFrame接受Component
:
public Component add(Component comp, int index)
所以你有很多方法可以解决你的问题:
改为JPanel
:
public class GamePanel extends JPanel {
public GamePanel() {
super.setBackground(Color.green);
}
}
您可以使用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");