Java Changing Font For All Buttons

2019-09-18 10:10发布

问题:

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);