我正在尝试使用两个面板的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);
}
}
答案 0 :(得分:1)
具有权重的东西是它们描述了如何处理额外的空间。组件具有首选的最小和最大尺寸,布局管理器在计算布局时使用这些尺寸。 GridBagLayout然后使用这些权重分割额外的空间。在你的情况下,我认为分割的空间等于900-button.getPreferredSize()。width。您可能将800像素分成320和480。
答案 1 :(得分:0)
这是使用GridBagLayout创建的面板的示例:(不要打扰swing工厂,只需创建一个组件)
private void buildSourcePanel() {
JPanel pnlSource = new JPanel();
GridBagLayout gbl_pnlSource = new GridBagLayout();
gbl_pnlSource.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0};
gbl_pnlSource.columnWidths = new int[]{0, 0, 100, 100, 25};
pnlSource.setLayout(gbl_pnlSource);
final JLabel lblFolderMask = swingFactory.createLabel(" SOURCE DIRECTORY ", null, null, SwingConstants.LEFT, SwingConstants.CENTER, true);
pnlSource.add(lblFolderMask, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, 10, 1, new Insets(5, 5, 5, 0), 0, 0));
txtSource = swingFactory.createTextField(null, "txtSource", null, SystemColor.textHighlight, SwingConstants.LEFT, false, true, "Source Directory");
pnlSource.add(txtSource, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, 10, 1, new Insets(5, 0, 5, 5), 0, 0));
final JButton btnBrowse = new JButton("Browse...");
btnBrowse.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 0, false), new EmptyBorder(5, 5, 5, 5)));
btnBrowse.setFont(new Font("Verdana", Font.BOLD, 14));
pnlSource.add(btnBrowse, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, 10, 1, new Insets(5, 0, 5, 5), 0, 0));
final JButton btnClear = new JButton("Clear...");
btnClear.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 0, false), new EmptyBorder(5, 5, 5, 5)));
btnClear.setFont(new Font("Verdana", Font.BOLD, 14));
pnlSource.add(btnClear, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, 10, 1, new Insets(5, 0, 5, 5), 0, 0));
lblStatus = swingFactory.createLabel(null, null, null, SwingConstants.CENTER, SwingConstants.CENTER, false);
pnlSource.add(lblStatus, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0, 10, 1, new Insets(5, 5, 5, 5), 0, 0));
}