Java更改所有按钮的字体

时间:2014-04-29 06:30:15

标签: java swing button fonts

我的程序使用了大量的JButton,我想知道如何更改特定面板中所有现有按钮的字体,而无需单独更改每个按钮的字体。 / p>

3 个答案:

答案 0 :(得分:3)

  

我想知道如何更改所有现有字体   特定面板内的按钮,无需单独更改   每个按钮的字体

从技术上讲,你不能,你需要能够迭代容器并单独更改每个按钮......

假设所有按钮都在一个容器上(并且不包含在多个子容器中),您可以简单地遍历给定容器中的所有组件,测试它们是否为JButton并应用新字体。

Font font = new Font("Arial", Font.BOLD, 48);
for (Component comp : getComponents()) {
    if (comp instanceof JButton) {
        ((JButton)comp).setFont(font);
    }
}

例如......

答案 1 :(得分:0)

您可以创建自己的扩展JButton的类并设置该类的字体,然后将其用于JPanel中的所有按钮:

class MyJButton extends JButton {

    MyJButton() {

        super();
        setFont(new Font("Arial", Font.BOLD, 40));
   }
}

您可以覆盖正在使用的构造函数。

答案 2 :(得分:0)

语法为

setFont(new Font("fontName", fontStyle, fontSize));

除非您使用自定义字体,否则它将是

setFont(font);