2017-04-05 78 views
1

我正在處理一個菜單,我想使它成爲可能的對象,所以我爲菜單JPanel對象創建了一個單獨的類。問題是它不想將它添加到我的主JPanel中。我做錯了什麼,我該如何解決?將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); 
    } 
} 

回答

1

你不能在一個類添加到您的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");