Search code examples
javaswingawtnimbus

NimbusLookAndFeel cannot be resolved to a variable


I am trying to learn the basic GUI using swing. When I tried to activate/set nimbus, the following error is shown "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel cannot be resolved to a variable". The error is shown in the com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel line in setLookAndFeel() method. I am using java build 1.7.0

import java.awt.FlowLayout;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.*;

public class swing1 extends JFrame {
    public swing1(){
        super("Title: Swing Project 1");
        //setLookAndFeel();
        setSize(225,80);
        setLookAndFeel();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        FlowLayout flo = new FlowLayout();
        JButton adds = new JButton ("Add");
        JButton minus = new JButton("Substract");
        JButton mult = new JButton ("Multiply");
        add(adds);
        add(minus);
        add(mult);
        setVisible(true);                   
    }

    private void setLookAndFeel() {
        // TODO Auto-generated method stub
        try {
            UIManager.setLookAndFeel(“com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel”);
        }
        catch (Exception exc) {
            //ignore
        }       
    }

    public static void main (String args   []){
        swing1 startSwing = new swing1();
    }
}

Solution

  • Literal String you define with " not with

    Also use this code to set Look and Feel.

    import javax.swing.UIManager.*;
    
    try {
        for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (Exception e) {
        // If Nimbus is not available, you can set the GUI to another look and feel.
    }
    

    From official Nimbus Look and Feel.

    Version Note: Do not set the Nimbus look and feel explicitly by invoking the UIManager.setLookAndFeel method because not all versions or implementations of Java SE 6 support Nimbus. Additionally, the location of the Nimbus package changed between the JDK 6 Update 10 and JDK 7 releases. Iterating through all installed look and feel implementations is a more robust approach because if Nimbus is not available, the default look and feel is used. For the JDK 6 Update 10 release, the Nimbus package is located at com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel.