001package jmri.util.swing;
002
003import java.awt.Color;
004import java.awt.Component;
005
006import javax.swing.JComponent;
007import javax.swing.JPanel;
008import javax.swing.JTabbedPane;
009
010/**
011 * Some utilities to turn a recursively component opacity and background transparent
012 * 
013 * @author Lionel Jeanson 2025
014 */
015public class TransparencyUtils {
016
017    /**
018     * Recursively set opacity of a component and its sub components
019     *
020     * @param jcomp The component on which to set opacity
021     *
022     */  
023    public static void setOpacityRec(JComponent jcomp) {
024        setOpacityRec(jcomp, true);
025    }
026
027    public static void setOpacityRec(JComponent jcomp, boolean transparency) {
028        if (jcomp instanceof JPanel || jcomp instanceof JTabbedPane) {
029            jcomp.setOpaque(!transparency);
030        }
031        setOpacityRec(jcomp.getComponents(), transparency);
032    }
033
034    private static void setOpacityRec(Component[] comps, boolean transparency) {
035        for (Component comp : comps) {
036            try {
037                if (comp instanceof JComponent) {
038                    setOpacityRec((JComponent) comp, transparency);
039                }
040            } catch (Exception e) {
041                // Do nothing, just go on
042            }
043        }
044    }
045
046    /**
047     * Recursively set a component and its sub components backgroud transparent
048     *
049     * @param jcomp The component on which to set a transparent background
050     *
051     */    
052    public static void setTransparentBackgroundRec(JComponent jcomp) {
053        if (jcomp instanceof JPanel || jcomp instanceof JTabbedPane)
054        {
055            jcomp.setBackground(new Color(0, 0, 0, 0));
056        }
057        setTransparentBackgroundRec(jcomp.getComponents());
058    }
059
060    /**
061     * Recursively set several components backgroud transparent.
062     *
063     * @param comps The components array to set.
064     *
065     */
066    private static void setTransparentBackgroundRec(Component[] comps) {
067        for (Component comp : comps) {
068            try {
069                if (comp instanceof JComponent) {
070                    setTransparentBackgroundRec((JComponent) comp);
071                }
072            } catch (Exception e) {
073                // Do nothing, just go on
074            }
075        }
076    }    
077}