BorderLayout.CENTER上GridBagLayout面板的垂直对齐

Sky*_*yfe 3 java swing alignment vertical-alignment gridbaglayout

我想要做的是在我的BorderLayout的中心放置一个GridBagLayout面板,并将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);
  }

}
Run Code Online (Sandbox Code Playgroud)

所以我尝试使用gridbagconstraints锚点将对齐垂直设置为北,顶部,但这似乎不起作用.我还尝试调整GridBagLayout面板本身的大小(使其具有布局的完整高度,100%,使用panel.setSize和setPreferredSize),然后使用gridbagconstraints.anchor垂直对齐其上的元素,但这不起作用无论是.

任何人都可以帮我解决这个问题吗?

提前致谢,

最诚挚的问候,Skyfe.

所以我的问题是

Mon*_*rlo 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);
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 我认为在这个例子中扩展 JFrame 是不必要的。 (2认同)