0

I want to align my two of my components to the top left corner of the window.

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

public class MainFrame extends JFrame {
    public MainFrame() {
    JPanel mainPanel = new JPanel(new BorderLayout());
    JPanel gridbagPanel = new JPanel();
    this.setLayout(new BorderLayout());

    gridbagPanel.setLayout(new GridBagLayout());
    GridBagConstraints gc = new GridBagConstraints();

    JLabel nameLabel = new JLabel(player.getName());
    nameLabel.setHorizontalAlignment(SwingConstants.CENTER);
    nameLabel.setFont(new Font("Serif",Font.PLAIN,24));
    mainPanel.add(nameLabel, BorderLayout.NORTH);

    JLabel money = new JLabel("Pinigai: "+new Integer(player.getMoney()).toString());
    gc.gridx = 0;
    gc.gridy = 0;
    gc.anchor = GridBagConstraints.PAGE_START;
    gc.insets = new Insets(2,0,0,2);
    gridbagPanel.add(money,gc);

    JLabel job = new JLabel("Darbas: "+new Integer(player.getSkin()).toString());
    gc.gridx = 0;
    gc.gridy = 1;
    gc.insets = new Insets(2,0,0,2);
    gc.anchor = GridBagConstraints.LINE_START;
    gridbagPanel.add(job, gc);

    mainPanel.setBorder(new EmptyBorder(10,10,10,10));
    mainPanel.add(gridbagPanel,BorderLayout.WEST);

    add(mainPanel);
    getContentPane().revalidate();
}

} It currently looks like this: Current view of the components

And I would like the lines with numbers in the top left corner.

Note that I'm aware that both JFrame("this" class) and the mainPanel are using BorderLayouts.

Another non-related question: When should I create a new GridBagConstraints object? Why can't I just store one in a private instance variable for all usage needed?

Justas S
  • 584
  • 4
  • 12
  • 34
  • 1
    For this and similar questions you should put the effort in to creating and posting an [MCVE](http://stackoverflow.com/help/mcve). Please read the link for the helpful details. Trust me, it really works well. – Hovercraft Full Of Eels Jan 09 '14 at 21:03
  • 2
    For [example](http://stackoverflow.com/a/13437388/230513). – trashgod Jan 09 '14 at 21:03
  • Well I edited it to something. I hope this will be easier to understand. – Justas S Jan 09 '14 at 21:15
  • You're using code not available to us making your code not compile nor run for us. Don't use player anything but instead make up hard coded data that shows your problem. Please re-read the link. – Hovercraft Full Of Eels Jan 09 '14 at 21:35

2 Answers2

6

The beauty of GridBagLayout, is that column/row sizes are not fixed (ie, not every row/column has to be the same size, like in GridLayout)

You can "encourage" certain components to occupy more space within their given area then others.

Things like weightx and weighty describe how much of the available space a row/column should occupy. Add in the NORTHWEST anchor constraint and you should begin to see the desired effect.

enter image description here

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class MainFrame extends JFrame {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new MainFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public MainFrame() {
        JPanel mainPanel = new JPanel(new BorderLayout());
        JPanel gridbagPanel = new JPanel();
        this.setLayout(new BorderLayout());

        gridbagPanel.setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();

        JLabel nameLabel = new JLabel("Bebras");
        nameLabel.setHorizontalAlignment(SwingConstants.CENTER);
        nameLabel.setFont(new Font("Serif", Font.PLAIN, 24));
        mainPanel.add(nameLabel, BorderLayout.NORTH);

        JLabel money = new JLabel("Pinigai: " + new Integer(66484).toString());
        gc.gridx = 0;
        gc.gridy = 0;
        gc.anchor = GridBagConstraints.NORTHWEST;
        gc.insets = new Insets(2, 0, 0, 2);
        gridbagPanel.add(money, gc);

        JLabel job = new JLabel("Darbas: " + new Integer(126).toString());
        gc.gridx = 0;
        gc.gridy = 1;
        gc.insets = new Insets(2, 0, 0, 2);
        gc.anchor = GridBagConstraints.NORTHWEST;
        gc.weightx = 1;
        gc.weighty = 1;
        gridbagPanel.add(job, gc);

        mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
        mainPanel.add(gridbagPanel, BorderLayout.WEST);

        add(mainPanel);
        getContentPane().revalidate();

    }
}

Normally, I would add a "filler" component into the component, using it to push all the other components to where I want them, but this will come down to what it is you want to achieve.

Take a look at How to use GridBagLayout for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • @MarkW Nothing wrong with `BoxLayout`, just utilising what the OP has available (and I like `GridBagLayout` ;)) – MadProgrammer Jan 09 '14 at 22:22
  • Great. I tried using **weight** before but I didn't specify the `NORTHWEST` anchor. I would use BoxLayout, but there will be much more components, which I believe will need it. – Justas S Jan 10 '14 at 10:57
2

Im more of a fan of Box Layouts to achieve this type of static positioning in swing. see the example below:

import java.awt.Dimension;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class main extends JFrame {

public static void main(String[] args) throws InterruptedException {
    main m = new main();
    m.setVisible(true);
}

public main() {
    // setup stuff
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setBounds(100, 100, 500, 500);

    // this is the panel I will add to the frame
    JPanel innerPanel = new JPanel();
    // give it a Y axis to stuff is added top to bottom
    innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.Y_AXIS));

    // this is a temp panel ill used to add the labels
    JPanel tPanel = new JPanel();
    // its an x axis to add stuff left to right
    tPanel.setLayout(new BoxLayout(tPanel, BoxLayout.X_AXIS));

    // create and add a label to the temp panel
    JLabel label = new JLabel("Some text");
    tPanel.add(label);
    // use our stretchy glue to fill the space to the right of the label
    tPanel.add(Box.createHorizontalGlue());

    // add the temp panel to the inner panel
    innerPanel.add(tPanel);
    // create a spacer with 0 width and 10 height
    innerPanel.add(Box.createRigidArea(new Dimension(0, 10)));

    // reinitialize the temp panel for another label
    tPanel = new JPanel();
    tPanel.setLayout(new BoxLayout(tPanel, BoxLayout.X_AXIS));
    label = new JLabel("Some other text");
    // add the other label to the temp panel
    tPanel.add(label);
    // more stretchy glue
    tPanel.add(Box.createHorizontalGlue());

    // add the temp panel
    innerPanel.add(tPanel);
    // add verticle stretchy glue to fill the rest of the space below the
    // labels
    innerPanel.add(Box.createVerticalGlue());

    // add to the frame
    this.add(innerPanel);
}

}
Mark W
  • 2,791
  • 1
  • 21
  • 44