java – BorderLayout. Vertical alignment of gridbaglayout panel on Center

What I want to do is to place a gridbaglayout panel in the center of my borderlayout and align the gridbaglayout panel (and / on the text) vertically to the top (because it automatically puts it in the middle, horizontal and vertical)

So I've basically tried (but in the end, the text of gridbaglayout is still in the middle of the page, not in the middle X and top 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,GridBagConstraints.VERTICAL,GridBagConstraints.NORTH);
    gb.add(content,gbc); //gbc is containing the GridBagConstraints
    this.add(gb,BorderLayout.CENTER);
  }

}

So I tried to use GridBagConstraints anchor to set the vertical alignment to north, top, but it didn't seem to work I also try to resize the gridbaglayout panel itself (make it have the full height of the layout, 100%, using panel.setsize and setpreferredsize), and then use GridBagConstraints Anchor vertically aligns the elements on it, but this does not work, either

Can anyone help me solve this problem?

Thank you in advance,

Best wishes, skyfe

So my question is

Solution

Before using, please carefully check the Javadoc. For each attribute of the GridBagConstraints class

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);
    }

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>