在BoxLayout中居中元素

时间:2014-05-30 23:09:44

标签: java layout jlabel boxlayout

我无法将lblConInfo置于中心位置,因为它是内联HTML。有谁知道怎么做?

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);
    }
}

1 个答案:

答案 0 :(得分:0)

BoxLayout.X_AXIS的构造函数中添加JLabel,如下所示:

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

详细了解How to Use BoxLayout

快照

enter image description here

相关问题