【发布时间】:2015-10-27 03:48:42
【问题描述】:
我只是想按照this 教程使用 GridBagLayout。
我无法得到我想要的。
我希望每个面板尽可能多地占用空间,但事实并非如此,我真的尝试了一切,按照Oracle Docs中的步骤进行操作
但结果总是一样的:
我真的不明白为什么布局不起作用。
我尝试更改 JFrame 的布局,将面板设置为 ContentPane(),尝试添加在两个网站上找到的约束,但似乎没有任何效果。
感谢您的帮助。
完整代码
public class Monitor extends JFrame{
// Menu
private JMenuBar bar = new JMenuBar();
private JMenu file = new JMenu("File");
private JMenuItem open = new JMenuItem("Open");
private JMenuItem exit = new JMenuItem("Exit");
private JPanel mainPanel = new JPanel();
private JPanel secondaryPanel;
private JPanel explorerPanel, tagPanel;
public Monitor(){
setTitle("");
setSize(750,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
initComps();
}
public void initComps(){
explorerPanel = new JPanel();
explorerPanel.setBackground(Color.BLACK);
explorerPanel.setPreferredSize(new Dimension(250,300));
tagPanel = new JPanel();
tagPanel.setBackground(Color.yellow);
tagPanel.setPreferredSize(new Dimension(250, 300));
secondaryPanel = new JPanel();
secondaryPanel.setBackground(Color.blue);
secondaryPanel.setPreferredSize(new Dimension(500, 600));
mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(750, 600));
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0 ; gbc.gridy = 0 ; gbc.gridwidth = 1 ; gbc.gridheight = 1;
mainPanel.add(explorerPanel, gbc);
gbc.gridx = 1 ; gbc.gridy = 0 ; gbc.gridwidth = 2 ; gbc.gridheight = 2;
mainPanel.add(secondaryPanel, gbc);
gbc.gridx = 0 ; gbc.gridy = 1 ; gbc.gridwidth = 1 ; gbc.gridheight = 1;
mainPanel.add(tagPanel, gbc);
this.setContentPane(mainPanel);
// Menu Bar
file.add(open);
exit.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
exit.setMnemonic('q');
file.add(exit);
bar.add(file);
setJMenuBar(bar);
}
public static void main(String[] args) {
new Monitor().setVisible(true);
}
}
编辑:
添加时
gbc.weightx = 1;
gbc.weighty = 1;
结果
【问题讨论】:
-
请参阅:madbean.com/anim/totallygridbag 和 miglayout.com,以免发疯。
-
@Yar 谢谢你的建议。你认为使用 GBL 有可能吗?
-
是的,这可能是可能的。但 MigLayout 让每个人都永远快乐。
-
@OlivierGrégoire 可能确实是最好的。既然问了这个问题,我等待一个正确的答案。我希望能学到更多东西。 :) 但无论哪种方式都感谢您的建议。
标签: java swing constraints layout-manager gridbaglayout