Terryn
Terryn

Reputation: 95

How to correctly "layout" a JLabel?

So previously I had created a JFrame, and successfully added a JLabel to its southern border.

I had begun working on a bigger project with a GUI, when I realized that adding a JLabel to a JPanel and adding that JPanel to a JFrame did not work the same way as simply adding a JLabel to a JFrame. I am new to programming with java graphics, and am not quite sure of all the differences between JPanels and JFrames. For some reason, upon running the code I have included below, the label just remains in the top center of the panel.

// tests adding a JLabel to a JPanel

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

import java.awt.BorderLayout;

public class Test extends JFrame
{
    public Test()
    {
        super("TestFrame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 500);

        // add JPanel with label to frame
        JPanel panel = new JPanel();
        JLabel label = new JLabel("Testing 123...");
        panel.add(label, BorderLayout.SOUTH);

        add(panel);

        setVisible(true);
    }

    public static void main(String[] args)
    {
        // create a new Test
        Test test = new Test();
    }
}

I have been researching to find an answer for a while now, but for some reason cannot find anything. I have also tried using SwingConstants when creating the JLabel but this throws an IllegalArgumentException regarding horizontalAlignment. I have looked this up as well but have found nothing.

Does anybody know the way to correctly format a JLabel inside of a JPanel?

Thanks!

Upvotes: 0

Views: 6717

Answers (2)

monty.py
monty.py

Reputation: 2789

You could also set the layout by using this:

    panel.setLayout(new BorderLayout());

If you aren´t sure which methods you need, you can simply just tipp in the variable and a dot and wait till you get suggestions, there you can click on a method once and get the api information which could help you a lot by solving such problems. Or you look into the api via your browser: click!

Upvotes: 0

Reimeus
Reimeus

Reputation: 159864

JPanel uses FlowLayout by default. You need to set the layout to BorderLayout to use its constraints

JPanel panel = new JPanel(new BorderLayout());

Upvotes: 2

Related Questions