Search code examples
javajpaneljlabelborder-layout

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!


Solution

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

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