Java Changing Font For All Buttons

亡梦爱人 提交于 2020-01-06 08:32:07

问题


My Program is using an immense amount of JButton's, I was wondering how I would be able to change the font of all existing buttons within a specific panel, without having to individually change the font for each button.


回答1:


I was wondering how I would be able to change the font of all existing buttons within a specific panel, without having to individually change the font for each button

Technically, you can't, you need to be able to iterate the container and change each button individually...

Assuming that all the buttons are on a single container (and not contained within multiple sub containers), you could simply iterate through all the components in the given container, test to see if they are a JButton and apply the new font.

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

For example...




回答2:


You can create your own class extending JButton and set the font for that class, then use it for all the buttons in the JPanel:

class MyJButton extends JButton {

    MyJButton() {

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

You can override whichever constructor you are using.




回答3:


The syntax would be

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

Unless you have a custom font you made, then it would be

setFont(font);


来源:https://stackoverflow.com/questions/23357142/java-changing-font-for-all-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!