2015-02-23 69 views
1

我目前正在开发一个允许用户选择外观和感觉的项目。 但是,当用户选择另一个外观并将其更改回原始CrossPlatformLookAndFeel时,按钮的边框消失。更改外观后,是否可以保留按钮的边框? (Java Swing)

代码:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import javax.swing.border.*; 

public class SSCCE { 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       final JFrame frame = new JFrame(); 
       final JButton button = new JButton("Button"); 
       button.setBorder(LineBorder.createBlackLineBorder()); 
       button.addActionListener(new ActionListener() { 
        @Override 
        public void actionPerformed(ActionEvent ev) { 
         try{ 
         UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 
          SwingUtilities.updateComponentTreeUI(frame); 
          UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); 
          SwingUtilities.updateComponentTreeUI(frame); 
         } catch (Exception ex) { 
          System.out.println(ex.getMessage()); 
         } 
        } 
       }); 
       // 
       frame.setLayout(new FlowLayout(FlowLayout.CENTER)); 
       frame.add(button); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 
} 

正如你看到的,你点击该按钮后,边框消失。

所以问题是:在改变外观和感觉后边界可以保留吗?我知道边框不会出现在WindowsLookAndFeel中,但是在外观和感觉恢复为默认的外观之后是否可以“重新出现”?

回答

2

上次我查了一下,PLAF中有各种各样的错误导致了这些奇怪的行为。特别是当从MetaL LAF改变时(但是一个好的swathe也与Nimbus有关)。

获取应用程序的唯一可靠方法。改变PLAF是:

  • 序列化用户选择的新PLAF(即作为全限定类名的String)。
  • 启动一个新进程,调用main(String[]),该进程将检查要使用的新PLAF的序列化字符串并使用它。
  • (可能将当前GUI的状态传递给新的GUI。)
  • 关闭当前的GUI。

正如您所看到的,获得“绝对稳定可靠”的PLAF更改非常麻烦。