代码：

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class CelsiusConverter implements ActionListener {

JFrame converterFrame;

JPanel converterPanel;

JTextField tempCelsius;

JLabel celsiusLabel, fahrenheitLabel;

JButton convertTemp;

public CelsiusConverter() {

converterFrame = new JFrame("摄氏－华氏温度转换器");

converterFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

converterFrame.setSize(new Dimension(120, 40));

converterPanel = new JPanel(new GridLayout(2, 2));

//添加小部件

addWidgets();

//设立默认按钮

converterFrame.getRootPane().setDefaultButton(convertTemp);

//把面板添加到窗口

converterFrame.getContentPane().add(converterPanel, BorderLayout.CENTER);

//显示窗口

converterFrame.pack();

converterFrame.setVisible(true);

}

/**

* 创建和添加窗口小部件

*/

private void addWidgets() {

//创建小部件

tempCelsius = new JTextField(2);

celsiusLabel = new JLabel("摄氏温度", SwingConstants.LEFT);

convertTemp = new JButton("转换");

fahrenheitLabel = new JLabel("华氏温度", SwingConstants.LEFT);

//监听转换按钮的事件

convertTemp.addActionListener(this);

//添加小部件到容器里

converterPanel.add(tempCelsius);

converterPanel.add(celsiusLabel);

converterPanel.add(convertTemp);

converterPanel.add(fahrenheitLabel);

celsiusLabel.setBorder(BorderFactory.createEmptyBorder(5,5,10,5));

fahrenheitLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

}

public void actionPerformed(ActionEvent event) {

//把摄氏温度解析为双精度并转换为华氏温度

int tempFahr = (int)((Double.parseDouble(tempCelsius.getText()))

* 1.8 + 32);

fahrenheitLabel.setText(tempFahr + " 华氏度");

}

//给事件分配线程安排一项作业：

//创建并显示这个 GUI

private static void createAndShowGUI() {

//Make sure we have nice window decorations.

JFrame.setDefaultLookAndFeelDecorated(true);

CelsiusConverter converter = new CelsiusConverter();

}

public static void main(String[] args) {

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

public void run() {

createAndShowGUI();

}

});

}

}