5

There is a similar question here: How to change the size of the font of a JLabel to take the maximum size

but it doesn't work in backwards.

So if you make JPanel bigger, font is growing, but if you make it smaller JLabel size and font remain as before

Check this Image

How to make Jlabel font growing according to JPanel size while resizing?

1
  • Did you try modyifying the code to fix the problem when the frame size shrinks?
    – camickr
    Feb 16, 2012 at 16:01

3 Answers 3

4

by using FontMetrics and TextLayout you can get this output (please read an comment in the code)

SwingUtilities can do that correctly too

I sugget to add a few pixels moreover on both directions

add ComponentListener to the container and on componentResized event recalculate FontMetrics again

enter image description here

import java.awt.*;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import javax.swing.*;

public class ShowFontMetrics extends JFrame {

    private static final long serialVersionUID = 1L;
    private JLabel lTime;

    public ShowFontMetrics() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel pane = new JPanel();
        pane.setLayout(new FlowLayout());
        lTime = new JLabel("88:88");
        lTime.setFont(new Font("Helvetica", Font.PLAIN, 88));
        FontMetrics fm = lTime.getFontMetrics(lTime.getFont());
        TextLayout layout = new TextLayout(lTime.getText(), lTime.getFont(), fm.getFontRenderContext());
        Rectangle2D bounds = layout.getBounds();
        Dimension d = lTime.getPreferredSize();
        d.height = (int) (bounds.getHeight() + 100);// add huge amount of pixels just for for fun
        d.width = (int) (bounds.getWidth() + 150);// add huge amount of pixels just for for fun
        lTime.setPreferredSize(d);
        lTime.setVerticalAlignment(SwingConstants.CENTER);
        lTime.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pane.add(lTime);
        setContentPane(pane);
    }

    public static void main(String[] arguments) {
        ShowFontMetrics frame = new ShowFontMetrics();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}
4
  • thank you. But it doesn't do what I meant.. The font of JLable have to be changed after JFrame resized. So if you make JFrame bigger/smaller - JLabel font has to be changed as well..
    – VextoR
    Feb 16, 2012 at 13:24
  • 1
    There's a related example that does this here.
    – trashgod
    Feb 16, 2012 at 13:26
  • I updated my answer (probably I not read your question...) for CompomentListener,
    – mKorbel
    Feb 16, 2012 at 13:27
  • @mKorbel still not working. Where is dynamic font setting? You set font: lTime.setFont(new Font("Helvetica", Font.PLAIN, 88)); So it static...
    – VextoR
    Feb 16, 2012 at 13:45
4

Like this? http://java-sl.com/tip_adapt_label_font_size.html

UPDATE:

The code as requested

import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

public class ResizeLabelFont extends JLabel {
    public static final int MIN_FONT_SIZE=3;
    public static final int MAX_FONT_SIZE=240;
    Graphics g;

    public ResizeLabelFont(String text) {
        super(text);
        init();
    }

    protected void init() {
        addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent e) {
                adaptLabelFont(ResizeLabelFont.this);
            }
        });
    }

    protected void adaptLabelFont(JLabel l) {
        if (g==null) {
            return;
        }
        Rectangle r=l.getBounds();
        int fontSize=MIN_FONT_SIZE;
        Font f=l.getFont();

        Rectangle r1=new Rectangle();
        Rectangle r2=new Rectangle();
        while (fontSize<MAX_FONT_SIZE) {
            r1.setSize(getTextSize(l, f.deriveFont(f.getStyle(), fontSize)));
            r2.setSize(getTextSize(l, f.deriveFont(f.getStyle(),fontSize+1)));
            if (r.contains(r1) && ! r.contains(r2)) {
                break;
            }
            fontSize++;
        }

        setFont(f.deriveFont(f.getStyle(),fontSize));
        repaint();
    }

    private Dimension getTextSize(JLabel l, Font f) {
        Dimension size=new Dimension();
        g.setFont(f);
        FontMetrics fm=g.getFontMetrics(f);
        size.width=fm.stringWidth(l.getText());
        size.height=fm.getHeight();

        return size;
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.g=g;
    }

    public static void main(String[] args) throws Exception {
        ResizeLabelFont label=new ResizeLabelFont("Some text");
        JFrame frame=new JFrame("Resize label font");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(label);

        frame.setSize(300,300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

}
1
  • I know this answer is old but it's also a link-only one. Can you copy the needed information from the link. Apr 28, 2015 at 18:05
0

ok, here is answer.

Let's take the code from here: How to change the size of the font of a JLabel to take the maximum size, answer from coobird

int componentWidth = label.getWidth();

We need to get width from the JFrame component, NOT from JLabel, because the code will no let opportunity to change size for the JLabel.

this will fix it:

int componentWidth = this.getWidth()-20; // '20' - according width of Jlabel to JFrame
2
  • 2
    for Container.getSize/getBounds you have to add Swing Timer, to avoiding caused flickering, only call for restart untill resize not ended,
    – mKorbel
    Feb 16, 2012 at 14:35
  • Why 20; shouldn't this be based on FontMetrics?
    – trashgod
    May 15, 2012 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.