I have a class that extends JPanel with several buttons on it. I would like to be able to set the font on all the buttons with one call to setFont(Font font); I defined the setFont method in the JPanel class as such:
public class MyPanel extends JPanel {
private JButton[] buttons = new JButton[10];
public MyPanel() {
for(int i = 0; i < 10; i++) {
buttons[i] = new JButton(""+i);
this.add(buttons[i]);
}
}
public void setFont(Font font) {
if(buttons != null) {
for(JButton b : buttons) {
b.setFont(font);
}
}
}
}
However, the font on the button never changes. I understand that setFont is called by the JPanel constructor, but I don't understand why, when I call it clearly AFTER the MyPanel object is created, the fonts aren't passed on to the buttons.
Thanks everyone!
Brent
If it is a repainting issue, minimize and re-open the gui to see if repaint fixes the problem. If not, you'll find that something is setting the font on the button after you are. Proabaly the best way to diagnose this is to create a subclass of JButton (temporarily) and use that to debug calls to setFont() - you'll be able to check the stack trace to see what is calling.
So,
private JButton[] buttons = new JButton[10];
buttons[i] = new JButton(""+i);
tobuttons[i] = new MyJButton(""+i);
Hope that helps
I believe trying the "repaint" method on each of the buttons should work.
If you want all subsequent buttons in the application to use a different font, you can set the default before instantiating the panel:
Addendum: A more focused approach might be to add instances of an extended
JButton
in your panel's constructor:The new buttons would always have the same font:
Don't know if you will find it any easier but you can also use:
for each of the buttons. Then when you want to change the font you can do:
and the buttons will inherit the font from the panel. I would guess you then need to invoke the repaint() method on the panel.