将字体传递给JPanel上的组件 [英] Passing font to components on a JPanel

查看:135
本文介绍了将字体传递给JPanel上的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展JPanel的类,上面有几个按钮。我希望能够通过一次调用setFont(Font font)来设置所有按钮的字体;我在JPanel类中定义了setFont方法:

  public class MyPanel extends JPanel {
private JButton []按钮=新的JButton [10];
$ b public MyPanel(){
for(int i = 0; i <10; i ++){
buttons [i] = new JButton(+ i);
this.add(buttons [i]);


$ b $ public void setFont(Font font){
if(buttons!= null){
for(JButton b:buttons){
b.setFont(font);



$ b

,按钮上的字体不会改变。我知道setFont是由JPanel构造函数调用的,但是我不明白为什么当我在创建MyPanel对象后清楚地调用它时,字体不会传递到按钮上。

感谢大家!

解决方案

如果您希望应用程序中的后续按钮使用不同的字体,您可以在实例化面板之前设置默认值:

  

附录:一个更加集中的方法可能是添加一个扩展 JButton



$ p $ buttons [i] = new MyButton(String.valueOf(i) );
this.add(buttons [i]);

新的按钮总是有相同的字体:

  private static class MyButton extends JButton {

private static final Font font = new Font(Dialog,Font.BOLD,24);

public MyButton(String text){
super(text);
this.setFont(font);
}
}


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 you want all subsequent buttons in the application to use a different font, you can set the default before instantiating the panel:

UIManager.put("Button.font", new FontUIResource("Dialog", Font.BOLD, 24));

Addendum: A more focused approach might be to add instances of an extended JButton in your panel's constructor:

buttons[i] = new MyButton(String.valueOf(i));
this.add(buttons[i]);

The new buttons would always have the same font:

private static class MyButton extends JButton {

    private static final Font font = new Font("Dialog", Font.BOLD, 24);

    public MyButton(String text) {
        super(text);
        this.setFont(font);
    }
}

这篇关于将字体传递给JPanel上的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆