Вопрос

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