首页 > 解决方案 > 仅更改某些组件的字体

问题描述

我有必要更改整个(swing)应用程序的字体样式和大小,但仅限于某些组件(主要是 JLabel、JTextArea、JTextField、JComboBox、JTable)。

我有这段代码

public void updateComponent(final Component component, final Font font){
    if(component instanceof JComponent){
        ((JComponent)component).updateUI();
    }
    if(component instanceof Container){
        Component[] children = ((Container)component).getComponents();
        for(Component child : children){
            updateComponent(child, font)
        }
    }

    if(component instanceof JLabel || component instanceof JTextArea || component instanceof JComboBox || component instanceof JTextField || component instanceof JTable){
        component.setFont(font);
    }
}

但是这段代码改变了所有JLabel、JTextArea、JTextField、JComboBox、JTable 的字体,而我只希望这些类的某些实例使用它。

我知道我可以定义和创建n个扩展原始类并检查它们的类,但我真的不喜欢为此创建n 个基本上是空的类。

public class JLabel2 extends JLabel{}
public class JTextArea2 extends JTextArea{}
...

if(component instanceof JLabel2 || component instanceof JTextArea2 || ...){

有没有更简单的解决方案?谢谢

标签: javaswing

解决方案


推荐阅读