Swing动态切换Look And Feel

canca10个月前 (07-25)Java技术222

这是最完整、最完美的解决方法

public static void setLookAndFeel(LookAndFeel lookAndFeel, java.util.List<Component>  components){
    if(components == null || components.isEmpty()) return;
    try {
        for(int i = 0 ; i < components.size() ; i++) {
            Component c = components.get(i);
            if(i == 0) {
                //改变全局设置
                JFrame.setDefaultLookAndFeelDecorated(lookAndFeel.getSupportsWindowDecorations());
                JDialog.setDefaultLookAndFeelDecorated(lookAndFeel.getSupportsWindowDecorations());
                UIManager.setLookAndFeel(lookAndFeel);
            }
            if (c instanceof JFrame) {
                JFrame frame = (JFrame) c;
                boolean isVisible = frame.isVisible();
                frame.dispose();
                frame.setUndecorated(lookAndFeel.getSupportsWindowDecorations());
                frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
                if(isVisible)frame.setVisible(true);
            } else if (c instanceof JDialog) {
                JDialog dialog = (JDialog) c;
                boolean isVisible = dialog.isVisible();
                dialog.dispose();
                dialog.setUndecorated(lookAndFeel.getSupportsWindowDecorations());
                dialog.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
                if(isVisible)dialog.setVisible(true);
            }
            if(c != null) SwingUtilities.updateComponentTreeUI(c);
        }
    }catch(Exception ex){
        throw new RuntimeException(ex);
    }
}


发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。