代码：

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class SwingApplication implements ActionListener {

private static String labelPrefix = "点击按钮数目：";

private int numClicks = 0;

final JLabel label = new JLabel(labelPrefix + "0 ");

//说明所使用的外观，有效值是：

//null (使用默认值), "Metal", "System", "Motif", "GTK+"

final static String LOOKANDFEEL = "Metal";

public Component createComponents() {

JButton button = new JButton("这是一个 Swing 按钮");

button.setMnemonic(KeyEvent.VK_I);

button.addActionListener(this);

label.setLabelFor(button);

/*

* 在顶层容器和它的内容物之间保持一定距离的一个简单的方式是：

* 把这些内容物放在一个 JPanel 容器里。

*/

JPanel pane = new JPanel(new GridLayout(0, 1));

pane.add(button);

pane.add(label);

pane.setBorder(BorderFactory.createEmptyBorder(

30, //顶

30, //左

10, //底

30) //右

);

return pane;

}

public void actionPerformed(ActionEvent e) {

numClicks++;

label.setText(labelPrefix + numClicks);

}

private static void initLookAndFeel() {

String lookAndFeel = null;

if (LOOKANDFEEL != null) {

if (LOOKANDFEEL.equals("Metal")) {

lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();

} else if (LOOKANDFEEL.equals("System")) {

lookAndFeel = UIManager.getSystemLookAndFeelClassName();

} else if (LOOKANDFEEL.equals("Motif")) {

lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";

} else if (LOOKANDFEEL.equals("GTK+")) { //1.4.2 里的新功能

lookAndFeel = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";

} else {

System.err.println("所使用的 LOOKANDFEEL 说明无法解析: "

+ LOOKANDFEEL);

lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();

}

try {

UIManager.setLookAndFeel(lookAndFeel);

} catch (ClassNotFoundException e) {

System.err.println("找不到所需要的外观类:"

+ lookAndFeel);

System.err.println("是否已经把 L&F 库包含到类路径里?");

System.err.println("使用默认的外观。");

} catch (UnsupportedLookAndFeelException e) {

System.err.println("在当前平台上无法使用当前外观 ("

+ lookAndFeel

+ ")");

System.err.println("使用默认的外观。");

} catch (Exception e) {

System.err.println("出于不明原因无法使用当前外观 ("

+ lookAndFeel

+ ")．");

System.err.println("使用默认的外观。");

e.printStackTrace();

}

}

}

/**

* 创建一个 GUI,并显示它

*/

private static void createAndShowGUI() {

//显示外观

initLookAndFeel();

//确保有一个窗口装饰

JFrame.setDefaultLookAndFeelDecorated(true);

//建立一个窗口

JFrame frame = new JFrame("Swing 应用");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

SwingApplication app = new SwingApplication();

Component contents = app.createComponents();

frame.getContentPane().add(contents, BorderLayout.CENTER);

//显示这个窗口

frame.pack();

frame.setVisible(true);

}

public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGUI();

}

});

}

}