Java Swing How to - Realize JLabel to resize font








Question

We would like to know how to realize JLabel to resize font.

Answer

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
/*from   w  w  w . j  a  v  a  2  s . c  om*/
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
  public static void main(String[] args) throws Exception {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    String s = "The quick brown fox jumps over the lazy dog!";
    Font font = new Font(Font.SERIF, Font.PLAIN, 24);

    JLabel l1 = new MyLabel(s);
    l1.setFont(font);
    f.setContentPane(l1);
    f.pack();

    f.setVisible(true);
  }
}

class MyLabel extends JLabel {

  public MyLabel(String s) {
    super(s);
  }

  @Override
  public void paintComponent(Graphics gr) {
    Color c = gr.getColor();
    setForeground(new Color(0, 0, 0, 0));
    super.paintComponent(gr);
    setForeground(c);
    gr.setColor(c);
    Graphics2D g = (Graphics2D) gr;
    g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    double pw = this.getPreferredSize().width;
    double ph = this.getPreferredSize().height;
    double w = this.getSize().width;
    double h = this.getSize().height;

    g.setColor(this.getForeground());

    AffineTransform stretch = AffineTransform.getScaleInstance(w / pw, h / ph);
    g.setTransform(stretch);
    g.drawString(getText(), 0, this.getFont().getSize());
  }
}