我正在编写一个GUI Builder,希望用户能够更改他构建的GUI的LookAndFeel。 LookAndFeel仅应在编辑器区域内的Components进行更改。应用程序的其余部分应保留在SystemLookAndFeel中。

很大的问题是,LookAndFeel是作为Singleton实现的,并且在应用程序过程中多次更改LookAndFeel会导致很多错误。

我开始尝试Buttons:
我尝试将ButtonUI设置为MetalButtonUI,但它们无法正确呈现。因此,我调试了JButton的默认paintComponent方法,并看到ButtonUI仍然需要UIDefaults,因为它们是WindowsUIDefaults,所以它们并不完整。

我当前的解决方案是设置MetalLookAndFeel,保存UIDefaults,然后将LookAndFeel更改为SystemLookAndFeel并保存这些UIDefaults,并且每次在编辑器中绘制一个Button时,都会交换UIDefaults。

这是代码:

public class MainClass{
    public static Hashtable systemUI;
    public static Hashtable metalUI;

    public static void main(String[] args) {
         EventQueue.invokeLater(new Runnable() {
             public void run() {
                 try {
                    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                    metalUI = new Hashtable();
                    metalUI.putAll(UIManager.getDefaults());

                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    systemUI = new Hashtable();
                    systemUI.putAll(UIManager.getDefaults());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /* ...
                 * Generate JFrame and other stuff
                 * ...
                 */
            }
        });
    }
}

public class MyButton extends JButton {
    public MyButton(String text) {
        super(text);
        ui = MetalButtonUI.createUI(this);
    }

    @Override public synchronized void paintComponent(Graphics g) {
        UIManager.getDefaults().putAll(Application.metalUI);

        super.paintComponent(g);

        UIManager.getDefaults().putAll(Application.systemUI);
    }
}


如您所见,here结果非常好。左侧是MetalLaF,其外观应在右侧,右侧是如何在应用程序中呈现的。渐变正确绘制,但“边框”和“字体”却不正确。

因此,我需要知道为什么不是LaF的所有元素都被应用到Button以及如何解决。

--

编辑:
我找到了一个丑陋的解决方案。创建Button之前,必须更改LookAndFeel,因为Graphics对象将在构造方法中创建。在调用超级构造函数之后,您可以将LookAndFeel改回来。

接下来,您需要在绘制/重新绘制组件之前更改LookAndFeel。我唯一能使它工作的地方是在super被调用之前在paintComponent中。您可以在调用super之后将其改回。

码:

import javax.swing.*;
import javax.swing.plaf.metal.MetalButtonUI;
import java.awt.*;

public class MainClass {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                JFrame f = new JFrame("Test");
                f.setDefaultCloseOperation(f.getExtendedState() | JFrame.EXIT_ON_CLOSE);

                try {
                    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                } catch (Exception ex) {
                }
                f.setLayout(new FlowLayout());

                f.add(new MyButton("MetalButton"));
                f.add(new JButton("SystemButton"));

                f.pack();
                f.setVisible(true);
            }
        });
    }
}

class MyButton extends JButton {
    public MyButton(String text) {
        super(text);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }
        ui = MetalButtonUI.createUI(this);
    }

    @Override public synchronized void paintComponent(Graphics g) {
        try {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());

            super.paintComponent(g);

            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }
    }
}


编辑2:
除非绝对必要,否则请勿使用此功能!

这是非常不稳定的。经过大量测试,当我只交换UIDefaults而不是整个LookAndFeel时,发现它的bug较少,但是我不建议您进行任何此类操作。

编辑3:
我发现最好的解决方案是使用JavaFX作为GUI。我将一个swing节点插入了Editor区域,现在可以根据需要多次修改swing组件的外观,而没有任何明显的副作用。

兰特:
如果要修改应用程序的样式,总是可以选择JavaFX。 CSS使它变得尽可能简单,没有任何副作用!



非常感谢

乔尼

最佳答案

免责声明

Swing的Look And Feel并非在首次启动后就进行了切换,实际上这是一种可能的怪异副作用。在正常情况下,某些外观和某些组件可能不喜欢您这样做,并且可能无法正常运行。

可能的解决方案

出于对智能的热爱,不要在paintComponent方法中更改UI默认设置(不要从任何paint方法中更改UI的状态,只绘画当前状态),这只是要求无尽的麻烦。

相反,在需要时使用UIManager.setLookAndFeel(,,,)SwingUtiltiies#updateComponentTreeUI并传入最顶层的容器

例如...

java - 通过交换UIDefaults更改外观-LMLPHP

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class LookAndFeelSwitcher {

    public static void main(String[] args) {
        new LookAndFeelSwitcher();
    }

    public LookAndFeelSwitcher() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.insets = new Insets(2, 2, 2, 2);

            add(new JLabel("I have a bad feeling about this"), gbc);
            add(new JTextField("When this blows up in your face, don't blame me"), gbc);

            UIManager.LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels();
            DefaultComboBoxModel model = new DefaultComboBoxModel(lafs);
            JComboBox cb = new JComboBox(model);
            cb.setRenderer(new LookAndFeelInfoListCellRenderer());
            add(cb, gbc);

            String name = UIManager.getLookAndFeel().getName();
            for (int index = 0; index < model.getSize(); index++) {
                UIManager.LookAndFeelInfo info = (UIManager.LookAndFeelInfo) model.getElementAt(index);
                if (info.getName().equals(name)) {
                    model.setSelectedItem(info);
                    break;
                }
            }

            cb.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    UIManager.LookAndFeelInfo info = (UIManager.LookAndFeelInfo) cb.getSelectedItem();
                    String className = info.getClassName();
                    try {
                        UIManager.setLookAndFeel(className);
                        SwingUtilities.updateComponentTreeUI(SwingUtilities.windowForComponent(TestPane.this));
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }

        public class LookAndFeelInfoListCellRenderer extends DefaultListCellRenderer {

            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                if (value instanceof UIManager.LookAndFeelInfo) {
                    UIManager.LookAndFeelInfo info = (UIManager.LookAndFeelInfo) value;
                    value = info.getName();
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }

        }

    }

}

关于java - 通过交换UIDefaults更改外观,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33617713/

10-09 14:10