Java Swing How to - Use Looped drawString to change the font size








Question

We would like to know how to use Looped drawString to change the font size.

Answer

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
/*  w w w  . j av a  2  s. com*/
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel() {
      @Override
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int y = 0;
        for (int size = 4; size <= 24; size += 2) {
          g.setFont(new Font("Arial", Font.BOLD, size));
          g.drawString("Name", 0, y);
          int heightOfFont = g.getFontMetrics().getHeight();
          y += heightOfFont;
        }
      }
      @Override
      public Dimension getPreferredSize() {
        return new Dimension(300, 300);
      }
    };
    frame.add(panel);
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
    frame.pack();

  }
}