我想摆动这个界面:
当我确定它时,我想要调整所有子面板和按钮的大小:
不仅要调整大小的主窗口。我正在使用GridBagLayout。而且我不知道如何以这种方式将GridBagLayout面板的边框粘贴到Frame的边框上,当我调整框架的大小时,面板也要调整大小。
答案 0 :(得分:9)
我通常使用嵌套布局。
JPanel
作为基础BorderLayout
。 JPanel
中,并将其添加到CENTER
的{{1}}。 BorderLayout
中。 JPanel
。 JPanel
添加到其中。 JPanel
添加到JPanel
。{/ li>的SOUTH
答案 1 :(得分:3)
要实现这一目标的属性,即在调整JFrame大小时,JPanel也应调整自身大小,将为GridBagConstraints.BOTH
。在我看来,你的左JButton 比右JButton 略小。如果您真的想通过 GridBagLayout 来实现这一目标,那么我在这里为您提供了一些示例代码,请查看并询问可能出现的任何问题:
import java.awt.*;
import javax.swing.*;
public class GridBagExample
{
private JPanel contentPane;
private void displayGUI()
{
JFrame frame = new JFrame("GridBag Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
JPanel centerPanel = new JPanel();
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.CYAN);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 1.0;
gbc.weighty = 0.9;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.BOTH; // appears to me this is what you wanted
contentPane.add(centerPanel, gbc);
JButton leftButton = new JButton("Left");
JButton rightButton = new JButton("Right");
gbc.gridwidth = 1;
gbc.gridy = 1;
gbc.weightx = 0.3;
gbc.weighty = 0.1;
contentPane.add(leftButton, gbc);
gbc.gridx = 1;
gbc.weightx = 0.7;
gbc.weighty = 0.1;
contentPane.add(rightButton, gbc);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new GridBagExample().displayGUI();
}
});
}
}