I have a series of JComponents following a look and feel, I then wish to temporarily set a new look and feel in order to add some new components before reverting it back to the original. The code below shows an example of three JButtons, in which the appearance of 'Button 1' and 'Button 3' should be identical, with 'Button 2' differing. The code supplied does revert the overall look and feel, however the lookandfeeldefaults
which are set manually (i.e. font the font) are lost. Cheers.
EDIT: Sorry, the question is slightly misleading: all of the look and feel changes happen before the panel is displayed, as seen in the example code. This question is different from the suggested duplicate as the issue here is re-loading the manually set (UIManager.getLookAndFeelDefaults().put(...)
) properties, as opposed to the overall look and feel. The underlying reason for this question is that I need to add a JButton with a filled background colour to a panel, and setBackground
sets only the border of a JButton when using the windows look and feel
whereas the cross platform look and feel
fills the background.
UPDATE: The solution is to use UIManager.getLookAndFeelDefaults().putAll(previousLF);
instead of setLookAndFeel. The code has been updated accordingly.
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);
}
});
}
}