How to make JLabel in java display in the centre of the monitor

37 Views Asked by At

I tired even the .setLocationRelativeTo(null) but i guess it only works with JFrame. i looked up everywhere but no information of google. I also tried scrolling through the methods but here are too many. Please help me. I also tried typing .set then scrolling to look at the methods.

1

There are 1 best solutions below

0
Mr. Polywhirl On BEST ANSWER

If you want to center the application window frame, use setLocationRelativeTo. If you want to center a label within a JPanel, you can use a layout manager for the panel and center the label using horizontalAlignment.

enter image description here

package org.example;

import java.awt.*;
import javax.swing.*;

public class CenterLabelApp implements Runnable {
    private JPanel mainPanel;

    protected CenterLabelApp() {
        this.mainPanel = new JPanel();

        setup();
    }

    private void setup() {
        // Panel
        this.mainPanel.setLayout(new BorderLayout());
        this.mainPanel.setPreferredSize(new Dimension(400, 300));

        // Label
        JLabel label = new JLabel("Hello, World!");
        label.setHorizontalAlignment(SwingConstants.CENTER); // Center the label horizontally
        this.mainPanel.add(label, BorderLayout.CENTER); // Center the label vertically
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Center Label App");
        frame.setContentPane(this.mainPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null); // Center the window
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new CenterLabelApp());
    }
}

You could also use the second param of the JLabel constructor to set alignment:

// Center the label horizontally
JLabel label = new JLabel("Hello, World!", SwingConstants.CENTER);