基本上我有一個充當容器的類。這是一個JFrame
,它的構造函數需要JPanel
。現在,我在容器類之外構建了各種JPanel。我有他們設計這種方式的具體原因,主要是與MVC設計模式。如何將JPanel添加到不同類的容器中?
我遇到的問題是,無論何時將JPanel
添加到容器,FROM容器類都顯示爲空白。沒有編譯錯誤。我看不出爲什麼它不會添加我要求的內容。我會後一些代碼,這是容器:
public class MainFrame {
private JFrame mainContainer = new JFrame("Frog Checkers");
private JPanel frame = new testFrame();
public void start() {
mainContainer(frame);
}
private JFrame mainContainer(JPanel frame) {
mainContainer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainContainer.setSize(925, 608);
mainContainer.setVisible(true);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
mainContainer.setLocation(dim.width/2 - mainContainer.getSize().width
/2, dim.height/2 - mainContainer.getSize().height/2);
mainContainer.setResizable(false);
mainContainer.add(frame);
return mainContainer;
}
}
這就是我想要添加一個JPanel的一個例子:
public class testFrame extends JPanel {
private JPanel testPanel = new JPanel()
private JButton testButton, anotherButton;
public testFrame() {
testPanel.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
testButton = new JButton("New Button");
constraints.gridx = 0; // Location on grid
constraints.gridy = 3; // Location on grid
constraints.gridwidth = 2; // How many grids the width will consume
constraints.gridheight = 1; // How many grids the length will consume
constraints.weightx = 1.0; // for resizing
constraints.weighty = 1.0; // for resizing
constraints.anchor = GridBagConstraints.SOUTHWEST; // Where it will be anchored
constraints.ipadx = 20; // Internal padding
constraints.ipady = 20; // Inernal padding
constraints.insets = new Insets(50,50,50,50);
testPanel.add(testButton, constraints);
anotherButton = new JButton("another Button");
constraints.gridx = 0; // Location on grid
constraints.gridy = 3; // Location on grid
constraints.gridwidth = 2; // How many grids the width will consume
constraints.gridheight = 1; // How many grids the length will consume
constraints.weightx = 1.0; // for resizing
constraints.weighty = 1.0; // for resizing
constraints.anchor = GridBagConstraints.SOUTHWEST; // Where it will be anchored
constraints.ipadx = 20; // Internal padding
constraints.ipady = 20; // Inernal padding
constraints.insets = new Insets(50, 50, 120, 80);
testPanel.add(anotherButton, constraints);
}
}
我使用的GridBagLayout,因爲我被告知無數次不使用空佈局。但如果有人知道使用空佈局的方式,請分享。爲了更清楚一點,所有這些代碼都可以工作,如果我把它作爲容器類中的一個方法,但我不想那樣。任何想法將不勝感激。
請參閱[使用多個JFrames,好/壞實踐?](http://stackoverflow.com/a/9554657/418556) – 2013-03-16 05:43:58