How to set look and feel via command line?

A LookAndFeel image taken from lookandfeelcast.com
Image Credit: lookandfeelcast.com
Here is how you can set the look and feel of a GUI application via the command prompt. The command line parameters helps us do this. Here is a simple program, that consists of the most typical GUI code. In this program, we will not set the look and feel, instead we set it via the command line. Here is how to do it.


import javax.swing.*;
import java.awt.*;
class LookAndFeelDemo extends JFrame
{
JButton jb;
JTextField jt;
JMenuBar mbar;
JMenu menu;
JMenuItem m1,m2,m3,m4,m5;

    public LookAndFeelDemo()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Look And Feel Demo");
        setLayout(new FlowLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        jb=new JButton("Button");
        jt=new JTextField(20);
        mbar=new JMenuBar();
        menu=new JMenu("Menu");
        m1=new JMenuItem("Item 1");
        m2=new JMenuItem("Item 2");
        m3=new JMenuItem("Item 3");
        m4=new JMenuItem("Item 4");
        m5=new JMenuItem("Item 5");
       
        menu.add(m1);
        menu.add(m2);
        menu.add(m3);
        menu.add(m4);
        menu.add(m5);
        mbar.add(menu);
       
        setJMenuBar(mbar);
       
        add(jb);
        add(jt);
       
        setSize(400,400);
        setLocationRelativeTo(null);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
                new LookAndFeelDemo();
            }
        });
    }
}

Compile the program using javac LookAndFeelDemo.java Later on, execute it in the following way,
java -Dswing.defaultlaf=javax.swing.plaf.nimbus.NimbusLookAndFeel LookAndFeelDemo.

The -Dswing.defaultlaf is a command line argument to the java interpreter. And the value is the look and feel class. When you do so, you will see the NimbusLookAndFeel in the application instead of the default metal look and feel which you'll get when you execute it in the routine way as java LookAndFeelDemo


Posted by at on

Tags: Java Tools, Swing Hacks,