Java Swing How to - Change JButton font dynamically








Question

We would like to know how to change JButton font dynamically.

Answer

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*from  w w w .  j a  v a2  s  . c  o m*/
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main extends JFrame {
   JButton b = new JButton("Add");
  int size = 10;
  public Main() {
    setSize(300, 150);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    add(b);
    b.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ev) {
        b.setFont(new Font("Dialog", Font.PLAIN, ++size));
        b.revalidate();
      }
    });
    setVisible(true);
  }

  public static void main(String[] args) {
    new Main();    
  }
}