Java/Swing JFC/Look Feel — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 06:46, 1 июня 2010

A Look-and-feel switcher

 
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
 * A Look-and-feel switcher.
 * 
 * @author Ian Darwin, http://www.darwinsys.ru/
 * @version $Id: LNFSwitcher.java,v 1.7 2004/03/07 04:03:15 ian Exp $
 */
public class LNFSwitcher {
  /** The frame. */
  protected JFrame theFrame;
  /** Its content pane */
  protected Container cp;
  /** Start with the Java look-and-feel, if possible */
  final static String PREFERREDLOOKANDFEELNAME = "javax.swing.plaf.metal.MetalLookAndFeel";
  protected String curLF = PREFERREDLOOKANDFEELNAME;
  protected JRadioButton previousButton;
  /** Construct a program... */
  public LNFSwitcher() {
    super();
    theFrame = new JFrame("LNF Switcher");
    theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    cp = theFrame.getContentPane();
    cp.setLayout(new FlowLayout());
    ButtonGroup bg = new ButtonGroup();
    JRadioButton bJava = new JRadioButton("Java");
    bJava.addActionListener(new LNFSetter(
        "javax.swing.plaf.metal.MetalLookAndFeel", bJava));
    bg.add(bJava);
    cp.add(bJava);
    JRadioButton bMSW = new JRadioButton("MS-Windows");
    bMSW.addActionListener(new LNFSetter(
        "com.sun.java.swing.plaf.windows.WindowsLookAndFeel", bMSW));
    bg.add(bMSW);
    cp.add(bMSW);
    JRadioButton bMotif = new JRadioButton("Motif");
    bMotif.addActionListener(new LNFSetter(
        "com.sun.java.swing.plaf.motif.MotifLookAndFeel", bMotif));
    bg.add(bMotif);
    cp.add(bMotif);
    JRadioButton bMac = new JRadioButton("Sun-MacOS");
    bMac.addActionListener(new LNFSetter(
        "com.sun.java.swing.plaf.mac.MacLookAndFeel", bMac));
    bg.add(bMac);
    cp.add(bMac);
    String defaultLookAndFeel = UIManager.getSystemLookAndFeelClassName();
    // System.out.println(defaultLookAndFeel);
    JRadioButton bDefault = new JRadioButton("Default");
    bDefault.addActionListener(new LNFSetter(defaultLookAndFeel, bDefault));
    bg.add(bDefault);
    cp.add(bDefault);
    (previousButton = bDefault).setSelected(true);
    theFrame.pack();
    theFrame.setVisible(true);
  }
  /* Class to set the Look and Feel on a frame */
  class LNFSetter implements ActionListener {
    String theLNFName;
    JRadioButton thisButton;
    /** Called to setup for button handling */
    LNFSetter(String lnfName, JRadioButton me) {
      theLNFName = lnfName;
      thisButton = me;
    }
    /** Called when the button actually gets pressed. */
    public void actionPerformed(ActionEvent e) {
      try {
        UIManager.setLookAndFeel(theLNFName);
        SwingUtilities.updateComponentTreeUI(theFrame);
        theFrame.pack();
      } catch (Exception evt) {
        JOptionPane.showMessageDialog(null,
            "setLookAndFeel didn"t work: " + evt, "UI Failure",
            JOptionPane.INFORMATION_MESSAGE);
        previousButton.setSelected(true); // reset the GUI to agree
      }
      previousButton = thisButton;
    }
  }
  public static void main(String[] argv) {
    new LNFSwitcher();
  }
}





awt.font.desktophints

 
 

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.util.Map;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/*
 * FontHints.java
 *
 * Created on May 1, 2007, 4:07 PM
 *
 * Copyright (c) 2007, Sun Microsystems, Inc
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the TimingFramework project nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 *
 * @author Chet
 */
public class FontHints extends JComponent {
    
    Map desktopHints = null;
    
    /** Creates a new instance of FontHints */
    public FontHints() {
        Toolkit tk = Toolkit.getDefaultToolkit();
        desktopHints = (Map)(tk.getDesktopProperty("awt.font.desktophints"));
    }
    
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, getWidth(), getHeight());
        g2d.setColor(Color.BLACK);
        
        g2d.drawString("Unhinted string", 10, 20);
        if (desktopHints != null) {
            g2d.addRenderingHints(desktopHints);
        }
        g2d.drawString("Desktop-hinted string", 10, 40);
    }
        
    
    private static void createAndShowGUI() {
        JFrame f = new JFrame("FontHints");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(200, 90);
        FontHints component = new FontHints();
        f.add(component);
        f.setVisible(true);
    }
    
    public static void main(String args[]) {
        Runnable doCreateAndShowGUI = new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        };
        SwingUtilities.invokeLater(doCreateAndShowGUI);
    }
}





Change Look and feel

 
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski     
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
public class ChangeLook {
  public static void main(String args[]) {
    final JFrame frame = new JFrame("Change Look");
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Object source = actionEvent.getSource();
        String lafClassName = null;
        if (source instanceof JComboBox) {
          JComboBox comboBox = (JComboBox) source;
          lafClassName = (String) comboBox.getSelectedItem();
        } else if (source instanceof JButton) {
          lafClassName = actionEvent.getActionCommand();
        }
        if (lafClassName != null) {
          final String finalLafClassName = lafClassName;
          Runnable runnable = new Runnable() {
            public void run() {
              try {
                UIManager.setLookAndFeel(finalLafClassName);
                SwingUtilities.updateComponentTreeUI(frame);
              } catch (Exception exception) {
                JOptionPane.showMessageDialog(frame,
                    "Can"t change look and feel",
                    "Invalid PLAF",
                    JOptionPane.ERROR_MESSAGE);
              }
            }
          };
          SwingUtilities.invokeLater(runnable);
        }
      }
    };
    Object newSettings[] = { "Button.background", Color.pink,
        "Button.foreground", Color.magenta };
    UIDefaults defaults = UIManager.getDefaults();
    defaults.putDefaults(newSettings);
    UIManager.LookAndFeelInfo looks[] = UIManager
        .getInstalledLookAndFeels();
    DefaultComboBoxModel model = new DefaultComboBoxModel();
    JComboBox comboBox = new JComboBox(model);
    JPanel panel = new JPanel();
    for (int i = 0, n = looks.length; i < n; i++) {
      JButton button = new JButton(looks[i].getName());
      model.addElement(looks[i].getClassName());
      button.setActionCommand(looks[i].getClassName());
      button.addActionListener(actionListener);
      panel.add(button);
    }
    comboBox.addActionListener(actionListener);
    Container contentPane = frame.getContentPane();
    contentPane.add(comboBox, BorderLayout.NORTH);
    contentPane.add(panel, BorderLayout.SOUTH);
    frame.setSize(350, 150);
    frame.setVisible(true);
  }
}





Change the look and feel

 
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class PlafTest extends JPanel implements ActionListener {
  private JButton metalButton = new JButton("Metal");
  private JButton motifButton = new JButton("Motif");
  private JButton windowsButton = new JButton("Windows");
  public PlafTest() {
    add(metalButton);
    add(motifButton);
    add(windowsButton);
    metalButton.addActionListener(this);
    motifButton.addActionListener(this);
    windowsButton.addActionListener(this);
  }
  public void actionPerformed(ActionEvent evt) {
    Object source = evt.getSource();
    String plaf = "";
    if (source == metalButton)
      plaf = "javax.swing.plaf.metal.MetalLookAndFeel";
    else if (source == motifButton)
      plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
    else if (source == windowsButton)
      plaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
    try {
      UIManager.setLookAndFeel(plaf);
      SwingUtilities.updateComponentTreeUI(this);
    } catch (Exception e) {
    }
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setTitle("PlafTest");
    frame.setSize(300, 200);
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    Container contentPane = frame.getContentPane();
    contentPane.add(new PlafTest());
    frame.show();
  }
}





Default look and feel can be set in a file called "swing.properties" located in the "<JAVAHOME>/lib" directory.

 
# Specify the default look and feel
swing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel





Get Installed Look And Feels

 
import javax.swing.UIManager;
public class ListPlafs {
  public static void main(String args[]) {
    UIManager.LookAndFeelInfo plaf[] = UIManager.getInstalledLookAndFeels();
    for (int i = 0, n = plaf.length; i < n; i++) {
      System.out.println("Name: " + plaf[i].getName());
      System.out.println("  Class name: " + plaf[i].getClassName());
    }
    System.exit(0);
  }
}





Get Swing Properties

 
import javax.swing.JMenu;
import javax.swing.UIManager;
public class GetIt {
  public static void main(String args[]) throws Exception {
    JMenu it = new JMenu();
    String classID = it.getUIClassID();
    System.out.println(classID);
    String className = (String) UIManager.get(classID);
    System.out.println(className);
    Class.forName(className);
    System.out.println(System.getProperty("swing.defaultlaf"));
    System.out.println(System.getProperty("swing.auxiliarylaf"));
    System.out.println(System.getProperty("swing.plaf.multiplexinglaf"));
    System.out.println(System.getProperty("swing.installedlafs"));
  }
}





Getting and Setting a Look and Feel

 

import javax.swing.LookAndFeel;
import javax.swing.UIManager;
public class Main {
  public static void main(String[] argv)throws Exception {
    // Get the currently installed look and feel
    LookAndFeel lf = UIManager.getLookAndFeel();
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
  }
}





Getting and Setting a Native Look and Feel

 

import javax.swing.UIManager;
public class Main {
  public static void main(String[] argv) throws Exception {
    String nativeLF = UIManager.getSystemLookAndFeelClassName();
    // Install the look and feel
    UIManager.setLookAndFeel(nativeLF);
  }
}





Highlighted Button

 
 

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RadialGradientPaint;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/*
 * HighlightedButton.java
 *
 * Created on May 1, 2007, 3:45 PM
 *
 * Copyright (c) 2007, Sun Microsystems, Inc
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the TimingFramework project nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * 
 * @author Chet
 */
public class HighlightedButton extends JButton {
  static final int HIGHLIGHT_SIZE = 18;
  BufferedImage highlight = new BufferedImage(HIGHLIGHT_SIZE, HIGHLIGHT_SIZE,
      BufferedImage.TYPE_INT_ARGB);
  /**
   * Creates a new instance of HighlightedButton
   */
  public HighlightedButton(String label) {
    super(label);
    // Get the Graphics for the image
    Graphics2D g2d = highlight.createGraphics();
    // Erase the image with a transparent background
    g2d.setComposite(AlphaComposite.Clear);
    g2d.fillRect(0, 0, HIGHLIGHT_SIZE, HIGHLIGHT_SIZE);
    g2d.setComposite(AlphaComposite.SrcOver);
    // Draw the highlight
    Point2D center = new Point2D.Float((float) HIGHLIGHT_SIZE / 2.0f, (float) HIGHLIGHT_SIZE / 2.0f);
    float radius = (float) HIGHLIGHT_SIZE / 2.0f;
    float[] dist = { 0.0f, .85f };
    Color[] colors = { Color.white, new Color(255, 255, 255, 0) };
    RadialGradientPaint paint = new RadialGradientPaint(center, radius, dist, colors);
    g2d.setPaint(paint);
    g2d.fillOval(0, 0, HIGHLIGHT_SIZE, HIGHLIGHT_SIZE);
    g2d.dispose();
  }
  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(highlight, getWidth() / 4, getHeight() / 4, null);
  }
  private static void createAndShowGUI() {
    JFrame f = new JFrame();
    f.getContentPane().setLayout(new FlowLayout());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(100, 100);
    f.add(new JButton("Standard"));
    f.add(new HighlightedButton("Highlighted"));
    f.setVisible(true);
  }
  public static void main(String args[]) {
    Runnable doCreateAndShowGUI = new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    };
    SwingUtilities.invokeLater(doCreateAndShowGUI);
  }
}





Look and feel string

  
    
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class MainClass {
  final static JLabel l = new JLabel();
  public static void main(String[] args) {
    selectLookAndFeel();
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel pane = new JPanel();
    pane.setLayout(new BorderLayout());
    JButton b = new JButton("Press Me!");
    b.setMnemonic(KeyEvent.VK_P);
    b.setToolTipText("Click this button to see a message.");
    pane.add("North", b);
    l.setLabelFor(b);
    pane.add("South", l);
    f.setContentPane(pane);
    f.setSize(300, 100);
    f.setVisible(true);
  }
  private static void selectLookAndFeel() {
    String actualName = UIManager.getCrossPlatformLookAndFeelClassName();
    //actualName = UIManager.getSystemLookAndFeelClassName();
    //actualName = "com.sun.java.swing.plaf.mac.MacLookAndFeel";
    //actualName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
    //actualName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
    try {
      UIManager.setLookAndFeel(actualName);
    } catch (Exception e) {
      System.err.println("Could not get " + actualName + " look and feel for some reason.");
    }
  }
}





Retrieve the cross-platform look and feel

 
import javax.swing.UIManager;
public class Main {
  public static void main(String[] argv) throws Exception {
    String javaLF = UIManager.getCrossPlatformLookAndFeelClassName();
    // Install the look and feel
    UIManager.setLookAndFeel(javaLF);
  }
}





Selecting different looks and feels

 
// : c14:LookAndFeel.java
// Selecting different looks & feels.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.ruponent;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.UIManager;
public class LookAndFeel extends JFrame {
  private String[] choices = { "eeny", "meeny", "Minnie", "Mickey", "Moe",
      "Larry", "Curly" };
  private Component[] samples = { new JButton("JButton"),
      new JTextField("JTextField"), new JLabel("JLabel"),
      new JCheckBox("JCheckBox"), new JRadioButton("Radio"),
      new JComboBox(choices), new JList(choices), };
  public LookAndFeel() {
    super("Look And Feel");
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    for (int i = 0; i < samples.length; i++)
      cp.add(samples[i]);
  }
  private static void usageError() {
    System.out.println("Usage:LookAndFeel [cross|system|motif]");
    System.exit(1);
  }
  public static void main(String[] args) {
    if (args.length == 0)
      usageError();
    if (args[0].equals("cross")) {
      try {
        UIManager.setLookAndFeel(UIManager
            .getCrossPlatformLookAndFeelClassName());
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (args[0].equals("system")) {
      try {
        UIManager.setLookAndFeel(UIManager
            .getSystemLookAndFeelClassName());
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (args[0].equals("motif")) {
      try {
        UIManager.setLookAndFeel("com.sun.java."
            + "swing.plaf.motif.MotifLookAndFeel");
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else
      usageError();
    // Note the look & feel must be set before
    // any components are created.
    run(new LookAndFeel(), 300, 200);
  }
  public static void run(JFrame frame, int width, int height) {
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(width, height);
    frame.setVisible(true);
  }
} ///:~





Set the look and feel using a system property on the command line

 
java -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel MyApp





Simple look and feel Example

 
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * @(#)SimpleExample.java  1.23 99/04/23
 *
 * Copyright (c) 1997-1999 by Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
 * modify and redistribute this software in source and binary code form,
 * provided that i) this copyright notice and license appear on all copies of
 * the software; and ii) Licensee does not utilize the software in a manner
 * which is disparaging to Sun.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
 * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
 * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
 * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 * 
 * This software is not designed or intended for use in on-line control of
 * aircraft, air traffic, aircraft navigation or aircraft communications; or in
 * the design, construction, operation or maintenance of any nuclear
 * facility. Licensee represents and warrants that it will not use or
 * redistribute the Software for such purposes.
 */
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
 * An application that displays a JButton and several JRadioButtons.
 * The JRadioButtons determine the look and feel used by the application.
 */
public class SimplelookandfeelExample extends JPanel {
    static JFrame frame;
    static String metal= "Metal";
    static String metalClassName = "javax.swing.plaf.metal.MetalLookAndFeel";
    static String motif = "Motif";
    static String motifClassName = 
      "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
    static String windows = "Windows";
    static String windowsClassName = 
      "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
    JRadioButton metalButton, motifButton, windowsButton;
    public SimplelookandfeelExample() {
  // Create the buttons.
  JButton button = new JButton("Hello, world");
        button.setMnemonic("h"); //for looks only; button does nada
  metalButton = new JRadioButton(metal);
        metalButton.setMnemonic("o"); 
  metalButton.setActionCommand(metalClassName);
  motifButton = new JRadioButton(motif);
        motifButton.setMnemonic("m"); 
  motifButton.setActionCommand(motifClassName);
  windowsButton = new JRadioButton(windows);
        windowsButton.setMnemonic("w"); 
  windowsButton.setActionCommand(windowsClassName);
  // Group the radio buttons.
  ButtonGroup group = new ButtonGroup();
  group.add(metalButton);
  group.add(motifButton);
  group.add(windowsButton);
        // Register a listener for the radio buttons.
  RadioListener myListener = new RadioListener();
  metalButton.addActionListener(myListener);
  motifButton.addActionListener(myListener);
  windowsButton.addActionListener(myListener);
  add(button);
  add(metalButton);
  add(motifButton);
  add(windowsButton);
    }

    /** An ActionListener that listens to the radio buttons. */
    class RadioListener implements ActionListener {
  public void actionPerformed(ActionEvent e) {
      String lnfName = e.getActionCommand();
            try {
    UIManager.setLookAndFeel(lnfName);
    SwingUtilities.updateComponentTreeUI(frame);
    frame.pack();
            } 
      catch (Exception exc) {
    JRadioButton button = (JRadioButton)e.getSource();
    button.setEnabled(false);
    updateState();
                System.err.println("Could not load LookAndFeel: " + lnfName);
            }
      
  }
    }
    public void updateState() {
   String lnfName = UIManager.getLookAndFeel().getClass().getName();
   if (lnfName.indexOf(metal) >= 0) {
       metalButton.setSelected(true);
   } else if (lnfName.indexOf(windows) >= 0) {
       windowsButton.setSelected(true);
   } else if (lnfName.indexOf(motif) >= 0) {
       motifButton.setSelected(true);
   } else {
       System.err.println("SimpleExample is using an unknown L&F: " + lnfName);
   }
    }
    public static void main(String s[]) {
  /* 
     NOTE: By default, the look and feel will be set to the
     Cross Platform Look and Feel (which is currently Metal).
     The user may someday be able to override the default
     via a system property. If you as the developer want to
     be sure that a particular L&F is set, you can do so
     by calling UIManager.setLookAndFeel(). For example, the
     first code snippet below forcibly sets the UI to be the
     System Look and Feel. The second code snippet forcibly
     sets the look and feel to the Cross Platform L&F.
     Snippet 1:
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception exc) {
            System.err.println("Error loading L&F: " + exc);
        }
     Snippet 2:
        try {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception exc) {
            System.err.println("Error loading L&F: " + exc);
              }
  */
  SimpleExample panel = new SimpleExample();
  
  frame = new JFrame("SimpleExample");
  frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {System.exit(0);}
  });
  frame.getContentPane().add("Center", panel);
  frame.pack();
  frame.setVisible(true);
  
  panel.updateState();
    }
}