基本上我有一个充当容器的类。它JFrame
有一个构造函数,它接受一个JPanel
. 现在,我在容器类之外构建了各种 JPanel。出于特定原因,我让它们以这种方式设计,主要与 MVC 设计模式有关。
我遇到的问题是,每当我将它添加JPanel
到容器中时,它从容器类中显示为空白。没有编译错误。我不明白为什么它不会添加我要求的内容。我会发布一些代码,这是容器:
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 是因为我多次被告知不要使用空布局。但是,如果有人知道使用空布局的方法,请分享。为了更清楚一点,如果我将所有这些代码都作为容器类中的一个方法,那么所有这些代码都可以工作,但我不希望这样。任何想法将不胜感激。