How to change JButton font dynamically in Java?


The following is an example to change JButton font dynamically:

Example

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SwingDemo extends JFrame {
   JButton button = new JButton("Change");
   int fontSize = 10;
   public SwingDemo() {
      setSize(500, 400);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      add(button);
      // changing font size dynamically on button click
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ev) {
            button.setFont(new Font("Dialog", Font.PLAIN, ++fontSize));
            button.revalidate();
         }
      });
      setVisible(true);
   }
   public static void main(String[] args) {
      new SwingDemo();
   }
}

Output

Click “Change” button above to change the font:

Updated on: 30-Jul-2019

705 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements