5

I create some label:

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

which look like this: enter image description here

As you can see there are big gap up and down. How I can reduce it ?

hudi
  • 15,555
  • 47
  • 142
  • 246
  • What when you don't pick a font size I can read from a mile off? – MarioDS Apr 14 '12 at 22:06
  • sorry randy but method setAlignmentY() doesn exist – hudi Apr 14 '12 at 22:29
  • I try: leftLabel.setVerticalAlignment(JLabel.TOP); leftLabel.setVerticalTextPosition(JLabel.TOP); leftLabel.setAlignmentY(TOP_ALIGNMENT); leftLabel.setBorder(BorderFactory.createEmptyBorder(-3 /*top*/, 0, 0, 0)); but still with no success – hudi Apr 14 '12 at 22:47

2 Answers2

10

You need to tweak the border insets,

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

Hopefully this gets you started in the right direction!

user1329572
  • 6,176
  • 5
  • 29
  • 39
2

the problem is probably within the properties of the newly created border. These borders have insets. That is the only thing I can think of to influence the gaps. Try to call a method on the border that changes these insets to [1,1,1,1].

MarioDS
  • 12,895
  • 15
  • 65
  • 121