Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical Align of GridBagLayout Panel on BorderLayout.CENTER

What I'm trying to do is place a GridBagLayout Panel on the center of my BorderLayout and vertical align the GridBagLayout panel ( /and text on it ) to the TOP ( because it automaticly puts it in the middle, horizontally AND vertically ).

So what I basicly tried ( but ended up having the text of the GridBagLayout still in the total middle of the page instead of 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, 0, GridBagConstraints.VERTICAL, GridBagConstraints.NORTH);
    gb.add(content, gbc); //gbc is containing the GridBagConstraints
    this.add(gb, BorderLayout.CENTER);
  }

}

So I tried to use the gridbagconstraints anchor to set the alignment vertically to the north, top, but that seems not to work. I also tried to resize the GridBagLayout panel itself ( to make it have full height of the layout, 100%, using panel.setSize and setPreferredSize ) and then vertically align the elements on it using the gridbagconstraints.anchor, but that didn't work either.

Can anyone help me out on this?

Thanks in advance,

Best Regards, Skyfe.

So my question is

like image 433
Skyfe Avatar asked Dec 03 '22 10:12

Skyfe


1 Answers

Take a careful look at the Javadoc of each property of the GridBagConstraints class before using it.

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

}
like image 93
Montecarlo Avatar answered Dec 06 '22 01:12

Montecarlo