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.

有帮助吗?

解决方案

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...

其他提示

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.

The syntax would be

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

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

setFont(font);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top