我有一系列具有外观和感觉的 JComponent,然后我希望暂时设置新的外观和感觉,以便在将其恢复为原始状态之前添加一些新组件。下面的代码显示了三个 JButton 的示例,其中“Button 1”和“Button 3”的外观应该相同,“Button 2”不同。提供的代码确实恢复了整体外观和感觉,但是 lookandfeeldefaults
手动设置的(即字体)会丢失。干杯。
编辑:抱歉,这个问题有点误导:所有外观和感觉更改都发生在面板显示之前,如示例代码所示。此问题与建议的重复问题不同,因为这里的问题是重新加载手动设置 ( UIManager.getLookAndFeelDefaults().put(...)
) 属性,而不是整体外观。这个问题的根本原因是我需要向面板添加一个具有填充背景颜色的 JButton,并且 setBackground
使用 windows look and feel
时仅设置 JButton 的边框而cross platform look and feel
填充背景。
更新:解决方案是使用 UIManager.getLookAndFeelDefaults().putAll(previousLF);
而不是 setLookAndFeel。代码已相应更新。
import java.awt.Color;
import java.awt.Font;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
public class test {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run() {
//Set initial look and feel.
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.getLookAndFeelDefaults().put("Button.font", new Font("Arial", Font.PLAIN, 20));
} catch (Exception e){}
JButton button1 = new JButton("1");
//change look and feel for button two.
UIDefaults previousLF = UIManager.getLookAndFeelDefaults();
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
UIManager.getLookAndFeelDefaults().put("Button.background", Color.BLUE);
} catch (Exception e) {}
JButton button2 = new JButton("2");
//Revert look and feel.
try {
UIManager.getLookAndFeelDefaults().putAll(previousLF);
} catch (Exception e) {}
JButton button3 = new JButton("3");
//Add buttons to panel and display for testing purposes.
JPanel testPanel = new JPanel();
testPanel.add(button1);
testPanel.add(button2);
testPanel.add(button3);
JOptionPane.showMessageDialog(null, testPanel);
}
});
}
}
最佳答案
- 您的代码错过了通知程序,如 Oracle 教程 How to Set the Look and Feel - Changing the Look and Feel After Startup 中所述
。
UIManager.setLookAndFeel(lnfName);
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
在您的情况下,也应该使用 JButton 的局部变量(而不是 JFrame)(通过使用 MetalLookAndFeel、WindowsLookAndFeel 对部分 JComponent 有效)
关于java - 暂时更改 Java Swing 中的默认外观,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25641780/