Search code examples
javalayoutjlabelboxlayout

Centering elements in a BoxLayout


I cannot get lblConInfo to center, due to it's inline HTML. Does anyone know how to do this?

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.IOException;

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

public class Streamer extends JFrame {
    private static String ip = "127.0.0.1";
    private static String key = "123456";

    public Streamer() throws IOException {
        JPanel streamPanel = new JPanel();
        streamPanel.setLayout(new BoxLayout(streamPanel, BoxLayout.Y_AXIS));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(200, 100);
        setResizable(false);
        Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
        setLocation(d.width - 200, 0);
        setAlwaysOnTop(true);

        add(streamPanel);
        addComponents(streamPanel);
        setTitle("RDV");
        setVisible(true);
        Capture.getScreen();
    }

    public void addComponents(JPanel pane) {
        JLabel lblClipboard = new JLabel("test");
        lblClipboard.setForeground(Color.blue);
        lblClipboard.setAlignmentX(Component.CENTER_ALIGNMENT);
        pane.add(lblClipboard);

        JLabel lblConInfo = new JLabel("<html><div align=\"center\">IP: " + ip + "<br>Key:" + key + "</div></html>");
        lblConInfo.setAlignmentX(Component.CENTER_ALIGNMENT);
        pane.add(lblConInfo);

        JButton btnCopy = new JButton("Copy to Clipboard");
        btnCopy.setAlignmentX(Component.CENTER_ALIGNMENT);
        pane.add(btnCopy);
    }
}

Solution

  • Add BoxLayout.X_AXIS in the constructor of JLabel as shown below:

    JLabel lblConInfo = new JLabel("<html><div align=\"center\">IP: " + ip + "<br>Key:" + key
            + "</div></html>", BoxLayout.X_AXIS);
    

    Read more about How to Use BoxLayout

    snapshot

    enter image description here