Vertical alignment of the GridBagLayout panel on BorderLayout.CENTER

What I'm trying to do is place the GridBagLayout panel in the center of my BorderLayout and vertically align the GridBagLayout panel (and the text on it) to TOP (because it automatically places it in the middle, horizontally and vertically)).

So, what I tried (but in the end I got the text GridBagLayout back in the middle of the page, and not in the middle of x and the top of 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.

, :

+3
3

, , Javadoc GridBagConstraints.

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

}
+12

setGBC(0, 0, GridBagConstraints.VERTICAL, GridBagConstraints.NORTH);

( "" ) gb . , , () . GridBagConstraints.NONE. GridBagLayout.

, - :

panel.add(button, BorderLayout.PAGE_START);

, .

+1

fill NONE weighty -0 (, 1.0). GridBag , , .

0

Source: https://habr.com/ru/post/1773880/


All Articles