我在一个JPanel中有3个组件,其中GridBagLayout是JPanel的LayoutManager,并在这3个组件上使用GridBagConstraints。
使用当前代码(如下所示),3个元素会正确地出现在面板上。问题是第一个组件是一个JLabel,它有时很长,如果是这样的话,它就会扩展,使其他两个组件变小。
我的目标是拥有一个GridBagLayout为1行4列的JPanel,其中第一个元素占用前两列,其他两个元素占用剩余的两列,并且这些元素不会扩展到它们的列之外。
private static void setConstraints(GridBagConstraints constraints, int gridx, int gridy, int weightx, Insets insets) {
constraints.gridx = gridx;
constraints.weightx = weightx;
constraints.insets = insets;
}
gridBagLayout = new GridBagLayout();
constraints = new GridBagConstraints();
centerPanel = new JPanel(gridBagLayout);
constraints.fill = GridBagConstraints.HORIZONTAL;
fileNameLabel = new JLabel("Resolving: '" + EngineHelpers.trimStringToFitPanel(urlTextField.getText(), 70) + "'");
setConstraints(constraints, 0, 0, 2, new Insets(0, 5, 5, 0));
gridBagLayout.setConstraints(fileNameLabel, constraints);
progressBar = new JProgressBar();
progressBar.setStringPainted(true);
setConstraints(constraints, 1, 0, 1, new Insets(0, 5, 5, 0));
gridBagLayout.setConstraints(progressBar, constraints);
cancelDownloadButton = new JButton("Cancel");
setConstraints(constraints, 2, 0, 1, new Insets(0, 0, 0, 0));
gridBagLayout.setConstraints(cancelDownloadButton, constraints);
centerPanel.add(fileNameLabel);
centerPanel.add(progressBar);
centerPanel.add(cancelDownloadButton);
提前感谢大家,抱歉愚蠢的问题!
您可能希望将按钮和进度条的weightx
设置为0。对于标签,将权重设置为1。这将保持按钮和进度条根本不展开,并让进度条占用所有额外的空间。
还要将进度条约束上的gridwidth
设置为2,这样它实际上使用了2列。
最后,根据centerpanel
放置的位置,它可能不会实际展开以填充容器。如果centerPanel被放置在带有BorderLayout的父级中,则它应该展开。若要确保,可以使用CenterPanel.SetBorder(BorderFactory.createlineBorder(Color.Red))
添加边框进行调试。这对按钮、标签和进度条也很有用。
介绍 (Introduction) GridBagLayout类以水平和垂直方式排列组件。 类声明 以下是java.awt.GridBagLayout类的声明: public class GridBagLayout extends Object implements LayoutManager2, Serializable 字段 (Field) 以下是java.awt.Bord
介绍 (Introduction) GridBagLayout类以水平和垂直方式排列组件。 Class 声明 (Class Declaration) 以下是java.awt.GridBagLayout类的声明 - public class GridBagLayout extends Object implements LayoutManager2, Serializable 字
主要内容:1 Java GridBagLayout的介绍,2 Java GridBagLayout的字段,3 Java GridBagLayout的方法,4 Java GridBagLayout的案例1,5 Java GridBagLayout的案例21 Java GridBagLayout的介绍 Java GridBagLayout类用于垂直,水平或沿其基线对齐组件。 组件的大小可能不同。每个GridBagLayout对象都维护一个动态的矩形单元格网格。每个组件占据一个或多个单元格(称为其显示
在具有1列和多行的面板中使用方框布局求解。
我正在尝试使用GridBagLayout。我需要一个垂直和水平居中的JLabel-这很容易,我甚至不需要创建任何GridBagConstraints。我还想在右下角放置一个JButton,当我尝试这样做时,我的中间面板会向左移动,或者按钮会向上移动。 我还试图使用这里描述的其他约束http://docs.oracle.com/javase/tutorial/uiswing/layout/gridb
我只想使用GridBagLayout布局组件,如图所示 我尝试了几个约束,但最终都没有得到预期的结果,所以我想知道,仅使用GridBagLayout是否真的可行。困难在于C1、C2和C3部件 C1和C2是一个组件,它将容纳其他组件,如JPanel。我已经设置了它们的最小尺寸和首选尺寸。C3是一个按钮 GUI无法调整大小 这个布局管理器我已经用了好几次了,但还是不太熟练,谢谢你的帮助。