我要做的是将GridBagLayout面板放在BorderLayout的中心,并将GridBagLayout面板(和/上的文本)垂直对齐到TOP(因为它自动将它放在中间,水平和垂直)。
所以我基本上尝试了(但最终让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。
所以我的问题是
答案 0 :(得分:12)
在使用之前,请仔细查看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);
}
}
答案 1 :(得分:1)
你的
setGBC(0, 0, GridBagConstraints.VERTICAL, GridBagConstraints.NORTH);
使组件(“内容”)垂直填充gb。这可能是您认为您的组件(内容)仍在中间的原因。尝试将其设置为GridBagConstraints.NONE
。
这会使您的内容与具有GridBagLayout的面板内的顶部对齐。
对于外部组件,您始终可以使用以下内容:
panel.add(button, BorderLayout.PAGE_START);
看看它是否有效。
答案 2 :(得分:0)
除了将fill
设置为NONE之外,还要将weighty
设置为非0值(例如1.0)。这告诉布局将GridBag列中的所有额外空间分配给该特定单元格,但由于标签本身锚定到北方并设置为不填充,因此额外空间将分配在标签下方。