我想用swing制作这个界面:
当我调整它时,我希望所有子面板和按钮都像这样调整大小:
不仅要调整主窗口的大小。我正在使用 GridBagLayout。而且我不知道如何将带有 GridBagLayout 的面板边框以这种方式粘贴到 Frame 的边框上,当我调整框架的大小时,面板也将被调整大小。
我想用swing制作这个界面:
当我调整它时,我希望所有子面板和按钮都像这样调整大小:
不仅要调整主窗口的大小。我正在使用 GridBagLayout。而且我不知道如何将带有 GridBagLayout 的面板边框以这种方式粘贴到 Frame 的边框上,当我调整框架的大小时,面板也将被调整大小。
我通常为此使用嵌套布局。
JPanel
和 aBorderLayout
作为基础。JPanel
中,并将其添加CENTER
到BorderLayout
.JPanel
的 s 中。JPanel
使用 1 行 2 列的 GridLayout创建另一个。JPanel
以正确的顺序将两个 s 添加到其中。JPanel
到SOUTH
.BorderLayout
实现这一点的属性,即当 JFrame 调整大小时,JPanel 也应该调整自身大小,将是GridBagConstraints.BOTH
. 在我看来,您的Left JButton比Right 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();
}
});
}
}