每當我將JFrame的佈局更改爲null,而不是實際設置它時,JPanel永遠不會被添加。我不確定爲什麼和我沒有找到關於此主題的足夠信息。這裏是我的JFrame類:在空佈局jframe上佈局佈局
public class Frame extends JFrame
{
public Frame() {
super("frame");
this.setLayout(null);
this.setIconImage(Toolkit.getDefaultToolkit().getImage(Main.class.getProtectionDomain().getClassLoader().getResource("icon.png")));
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(1250, 550);
this.getContentPane().setBackground(Color.GRAY);
}
}
此處,我實例化的JFrame:
public static Frame frame;
public static void initialize()
{
frame = new Frame();
CardLayout cardLayout = new CardLayout();
PanelContainer panelContainer = new PanelContainer(cardLayout);
panelContainer.setLayout(cardLayout);
JPanel panel1 = new Panel1();
JPanel panel2 = new Panel2();
panelContainer.add(panel1, "panel1");
panelContainer.add(panel2, "panel2");
cardLayout.show(panelContainer, "panel1");
gui.add(panelContainer, null);
gui.validate();
gui.setVisible(true);
}
這裏的面板容器類:
public class PanelContainer extends JPanel
{
public PanelContainer(CardLayout cardLayout)
{
super(cardLayout);
this.setVisible(true);
}
}
最後這裏是面板1和2,他們有相同的代碼:
public class Panel1 extends JPanel
{
public Panel1()
{
super();
this.setBackground(Color.GRAY);
addButtons(this);
}
public static void addButtons(FrontPanel panel)
{
JButton testButton = new JButton(new ImageIcon(Images.TestImage);
testButton (30,30);
testButton (0,0);
panel.addtestButton
}
}
謝謝您的時間和幫助!
哎呀抱歉,我錯誤地轉載了它,gui應該是框架。對不起,對於過度使用靜態的「一切」;我是新來的Java,我試圖使用靜態更好,問題是我不完全知道它的意義。另一件事是我不使用佈局,因爲我想要控制所有的東西,在Oracle文檔中查找我沒有找到能夠讓我這樣做的佈局。也許你可以建議一些東西給我使用?謝謝你的幫助! – SuperBrea 2014-09-11 16:54:03
@SuperBrea:請參閱編輯回答。 – 2014-09-11 16:58:22