如何在 Java 中动态更改 JButton 字体?

java 8object oriented programmingprogramming

以下是动态更改 JButton 字体的示例:

示例

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);
      // 单击按钮时动态更改字体大小
      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();
   }
}

输出

点击上方的"更改"按钮更改字体:


相关文章