改变JButton的外观和感觉

时间:2012-02-20 16:00:14

标签: swing jbutton nimbus

我想在我的应用程序中使用nimbus按钮样式。我不想改变L& F.只需更改按钮的L& F即可使用nimbus L& F.有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

可能有更好的方法,但以下实用程序类应该适合您:

import javax.swing.JButton;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;


public class NimbusButton {
    private static LookAndFeel nimbus;

    public static JButton generateNimbusButton() {
        try {
            LookAndFeel current = UIManager.getLookAndFeel(); //capture the current look and feel

            if (nimbus == null) { //only initialize Nimbus once
                for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
                nimbus = UIManager.getLookAndFeel();
            }
            else
                UIManager.setLookAndFeel(nimbus); //set look and feel to nimbus
            JButton button = new JButton(); //create the button
            UIManager.setLookAndFeel(current); //return the look and feel to its original state
            return button;
        }
        catch (Exception e) {
            e.printStackTrace();
            return new JButton();
        }
    }
}

generateNimbusButton()方法将外观更改为Nimbus,创建按钮,然后将外观更改为调用方法时的内容。