java - 如何更改 Swing 标签中的间隙

标签 java swing jlabel

我创建了一些标签:

leftLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
leftLabel.setFont(new Font(FONT, Font.PLAIN, 280));
leftLabel.setBorder(BorderFactory.createTitledBorder("aaa"));
leftLabel.setText("0");

看起来像这样:enter image description here

如您所见,上下差距很大。我怎样才能减少它?

最佳答案

你需要调整边框插入,

import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;

public final class TitledBorderDemo {
    private static void createAndShowGUI(){
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        frame.add(new TitledLabel(String.valueOf(0)));
        frame.pack();
        frame.setVisible(true);
    }

    private static class TitledLabel extends JLabel{
        private static final long serialVersionUID = 1L;
        private static final String TITLE = "aaa";

        TitledLabel(String text){
            super(text);
            setAlignmentX(Component.CENTER_ALIGNMENT);
            setFont(new Font("Arial", Font.PLAIN, 280));
            setBorder(new TitledBorder(TITLE){
                private static final long serialVersionUID = 1L;

                @Override
                public Insets getBorderInsets(Component c, Insets insets){
                    // arbitrary insets for top and bottom.
                    return new Insets(insets.top - 45, insets.left, insets.bottom - 55, insets.right);
            }});

        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                createAndShowGUI();             
            }
        });
    }
}

enter image description here

希望这能让您朝着正确的方向开始!

关于java - 如何更改 Swing 标签中的间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10157704/

相关文章:

java - 从 ActionPerformed 中的另一个类导入代码

java - JPanel 中的 GridBagLayout,组件不改变 x || y 位置

java: JTextField 的默认文档总是 PlainDocument 吗?

java - EventListenerList 相对于 Vector 的优势

java - 如何添加 JButton 和 JLabels 而不会发生冲突?

java - 如何修复 JLabel 透明度错误?

java - IBM Bluemix : Will it work for a Spring-MVC , Postgresql 与我们的域名

java - 如何编写可以提取 JAR 文件并将其数据存储在指定目录(位置)的 Java 程序?

java - 使用Java和sikuli对Excel进行排序并粘贴到网页上

java - 从 ArrayList 到 Hashmap