![](/img/trans.png)
[英]GridBagLayout in a BorderLayout problem : no display in BorderLayout.CENTER
[英]Vertical Align of GridBagLayout Panel on BorderLayout.CENTER
我想要做的是在我的 BorderLayout 的中心放置一个 GridBagLayout 面板,并将 GridBagLayout 面板(/和上面的文本)垂直对齐到顶部(因为它会自动将它放在中间,水平和垂直)。
所以我基本上尝试过(但最终使 GridBagLayout 的文本仍然在页面的中间而不是中间 x 和顶部 y):
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import javax.imageio.*;
import javax.swing.BorderFactory;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JApplet implements MouseListener, ActionListener {
public void init() {
//create borderlayout
this.setLayout(new BorderLayout());
//create a GridBagLayout panel
JPanel gb = new JPanel(new GridBagLayout());
JLabel content = new JLabel("Some text");
//set GridBagConstraints (gridx,gridy,fill,anchor)
setGBC(0, 0, GridBagConstraints.VERTICAL, GridBagConstraints.NORTH);
gb.add(content, gbc); //gbc is containing the GridBagConstraints
this.add(gb, BorderLayout.CENTER);
}
}
因此,我尝试使用 gridbagconstraints 锚点将对齐垂直设置为北、顶,但这似乎不起作用。 我还尝试调整 GridBagLayout 面板本身的大小(使其具有布局的完整高度,100%,使用 panel.setSize 和 setPreferredSize ),然后使用 gridbagconstraints.anchor 垂直对齐其上的元素,但这不起作用任何一个。
任何人都可以帮我解决这个问题吗?
提前致谢,
最好的问候, Skyfe。
所以我的问题是
在使用之前,请仔细查看GridBagConstraints
类的每个属性的 Javadoc。
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame {
public static void main(String arg[]) {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JPanel gb = new JPanel(new GridBagLayout());
JLabel content = new JLabel("Some text");
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTH;
gbc.weighty = 1;
gb.add(content, gbc); // gbc is containing the GridBagConstraints
frame.add(gb, BorderLayout.CENTER);
frame.setVisible(true);
}
}
除了将fill
设置为 NONE 之外,还将weighty
设置为非 0 值(例如 1.0)。 这告诉布局将 GridBag 列中的所有额外空间分配给该特定单元格,但由于标签本身锚定在北方并设置为不填充,额外的空间将分配在标签下方。
您的
setGBC(0, 0, GridBagConstraints.VERTICAL, GridBagConstraints.NORTH);
正在使组件(“内容”)垂直填充 gb。 这可能就是为什么您认为您的组件(内容)仍在中间的原因。 尝试将其设置为GridBagConstraints.NONE
。 这会将您的内容与具有 GridBagLayout 的面板内的顶部对齐。
对于外部组件,您始终可以使用以下内容:
panel.add(button, BorderLayout.PAGE_START);
看看它是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.