我试图让带有两个面板的 GridBagLayout 分别占框架的 40% 和 60%,同时能够在其中包含组件,但这很麻烦。
当我没有将按钮放置在面板内时,它的工作方式就像我想要的那样。
不太确定我做错了什么,我尝试将按钮的创建移动到 GridBagLayout 上创建面板的位置,但它仍然不起作用。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test{
public void display(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,650);
frame.setVisible(true);
JPanel test = new JPanel();
test.setLayout(new GridBagLayout());
GridBagConstraints c= new GridBagConstraints();
JPanel left= new JPanel();
JPanel right= new JPanel();
c.fill = GridBagConstraints.VERTICAL - GridBagConstraints.HORIZONTAL;
c.weightx = 0.4;
c.gridx = 1;
c.weighty = 1;
test.add(left,c);
c.weightx = .6;
c.gridx = 2;
test.add(right,c);
JButton button= new JButton("A button");
left.add(button,c);//If I do not add this, then it shows how I want it to be
frame.add(test);
}
}
最佳答案
权重的作用在于它们描述了如何处理额外的空间。组件具有布局管理器在计算布局时使用的首选尺寸、最小尺寸和最大尺寸。然后 GridBagLayout 使用这些权重分割额外的空间。在你的情况下,我认为分割的空间等于 900-button.getPreferredSize().width。您可能会将 800 个像素分割为 320 和 480 个像素。
关于Java GridBagLayout 内含组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8866891/