如何设置jframe外观

时间:2012-03-02 22:09:02

标签: java swing jframe look-and-feel uimanager

我对把它放在哪里感到困惑:

try {
    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e){

}

我没有延长JFrame类但使用JFrame f = new JFrame(); 谢谢:D

5 个答案:

答案 0 :(得分:12)

注意:这不是问题的答案( 设置LAF)。相反,它正在以一种独立于其包名的方式回答 how-to 设置LAF的问题。在班级被移动的情况下简化生活,如f.i.从com.sun *到javax.swing的Nimbus。

基本方法是查询UIManager以获取其安装的LAF,循环遍历它们直到找到匹配并设置它。这里是在SwingX中实现的方法:

/**
 * Returns the class name of the installed LookAndFeel with a name
 * containing the name snippet or null if none found.
 * 
 * @param nameSnippet a snippet contained in the Laf's name
 * @return the class name if installed, or null
 */
public static String getLookAndFeelClassName(String nameSnippet) {
    LookAndFeelInfo[] plafs = UIManager.getInstalledLookAndFeels();
    for (LookAndFeelInfo info : plafs) {
        if (info.getName().contains(nameSnippet)) {
            return info.getClassName();
        }
    }
    return null;
}

用法(此处无异常处理)

String className = getLookAndFeelClassName("Nimbus");
UIManager.setLookAndFeel(className); 

答案 1 :(得分:11)

最常见的地方是,在你的静态void main(String [] args)方法中。 像这样:

public static void main(String[] args) {
    try { 
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); 
    } catch(Exception ignored){}

    new YourClass(); //start your application
}  

了解更多信息请查看此站点: http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

答案 2 :(得分:9)

UIManager.setLookAndFeel()不适用于已创建的组件。这是为应用程序中的每个窗口设置外观的好方法。这将在程序中的所有打开的Windows上设置它。创建的任何新窗口都将使用UIManager设置的内容。

    UIManager.setLookAndFeel(lookModel.getLookAndFeels().get(getLookAndFeel()));
    for(Window window : JFrame.getWindows()) {
        SwingUtilities.updateComponentTreeUI(window);
    }

答案 3 :(得分:2)

您可以在创建JFrame之后将此块放在main方法中,或者在扩展JFrame的类的构造函数中放置。


    try
    {
        //Set the required look and feel
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        //Update the component tree - associate the look and feel with the given frame.
        SwingUtilities.updateComponentTreeUI(frame);
    }//end try
    catch(Exception ex)
    {
        ex.printStackTrace();
    }//end catch

答案 4 :(得分:0)

   try {
        for (javax.swing.UIManager.LookAndFeelInfo info :  javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
     } catch (ClassNotFoundException | InstantiationException || javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(  Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }