set Font to JComponent - Java Swing

Java examples for Swing:JComponent

Description

set Font to JComponent

Demo Code


//package com.java2s;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.plaf.basic.BasicComboBoxRenderer;

import java.awt.*;

public class Main {
    public static void setFont(JComponent component, Font font,
            ComponentOrientation componentOrientation) {
        component.setFont(font);/*from   ww w  . j  a v  a2s. c  om*/

        if (component instanceof JTextField) {
            component.setComponentOrientation(componentOrientation);
        }

        if (component instanceof JTextArea) {
            component.setComponentOrientation(componentOrientation);
        }

        if (component instanceof JTextPane) {
            component.setComponentOrientation(componentOrientation);
        }

        if (component instanceof JScrollPane) {
            for (Component cmp : component.getComponents()) {
                setFont((JComponent) cmp, font, componentOrientation);
            }
        }

        if (component instanceof JTree) {
            component.setComponentOrientation(componentOrientation);
        }

        if (component instanceof JComboBox) {
            component.setComponentOrientation(componentOrientation);
            JComboBox comboBox = (JComboBox) component;
            ((BasicComboBoxRenderer) comboBox.getRenderer())
                    .setHorizontalAlignment(SwingConstants.RIGHT);
            ((BasicComboBoxRenderer) comboBox.getRenderer())
                    .setAutoscrolls(true);
            comboBox.setMaximumRowCount(20);
        }

        /* if(component instanceof JLabel) {
             ((JLabel)component).setHorizontalTextPosition(SwingConstants.RIGHT);
         }*/

        if (component instanceof JPanel) {
            JPanel panel = (JPanel) component;
            if (panel.getBorder() != null
                    && panel.getBorder() instanceof TitledBorder) {
                ((TitledBorder) panel.getBorder()).setTitleFont(font);
                panel.setComponentOrientation(componentOrientation);
            }
            for (Component cmp : component.getComponents()) {
                setFont((JComponent) cmp, font, componentOrientation);
            }
        }

        if (component instanceof JTabbedPane) {
            JTabbedPane tabbedPane = (JTabbedPane) component;
            int tabCount = tabbedPane.getTabCount();
            for (int i = 0; i < tabCount; i++) {
                setFont((JComponent) tabbedPane.getComponentAt(i), font,
                        componentOrientation);
            }
        }
    }
}

Related Tutorials