13.将摄氏温度转换成华氏温度

效果:

输入25,点“转换温度”:

 

点“清空数据”:

代码:

CelsiusConverter.java

package com.lvshitech.gui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class CelsiusConverter implements ActionListener {
	
	JFrame frame;							// 框架
	JPanel panel;							// 面板
	JTextField tempCelsius;					// 文本框
	JLabel celsiusLabel, fahrenheitLabel;	// 标签
	JButton convertButton;					// 转换按钮
	JButton clearButton;					// 清空按钮
	
	public CelsiusConverter() {
		// 初始化控件
		frame = new JFrame("温度转换");
		panel = new JPanel();
		panel.setLayout(new GridLayout(2, 2));
		tempCelsius = new JTextField();
		celsiusLabel = new JLabel("摄氏温度 = ");
		convertButton = new JButton("转换温度");
		clearButton = new JButton("清空数据");
		fahrenheitLabel = new JLabel("?华氏温度");
		
		// 设置按钮命令符号
		convertButton.setActionCommand("convert");
		clearButton.setActionCommand("clear");
		
		// 将所有控件添加到面板
		panel.add(tempCelsius);
		panel.add(celsiusLabel);
		panel.add(fahrenheitLabel);
		panel.add(convertButton);
		panel.add(clearButton);
		
		// 将面板添加到容器
		Container container = frame.getContentPane();
		container.add(panel, BorderLayout.CENTER);
		
		// 按钮事件
		convertButton.addActionListener(this);
		clearButton.addActionListener(this);
		
		// 框架样式设置
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//frame.pack();
		frame.setSize(300, 100);
		frame.setVisible(true);
	}

	// 实现监听器接口
	@Override
	public void actionPerformed(ActionEvent e) {
		// 温度转换
		double tempF;
		String text = tempCelsius.getText();
		if ("convert".equals(e.getActionCommand())) {
			if (!"".equals(text)) {
				tempF = (Double.parseDouble(text)) * 1.8 + 32;
				fahrenheitLabel.setText(tempF + " 华氏温度");
			}
		}
		
		// 清空数据
		if ("clear".equals(e.getActionCommand())) {
			tempCelsius.setText("");
			fahrenheitLabel.setText("?华氏温度");
		}
	}
	
	// 主方法
	public static void main(String[] args) {
		CelsiusConverter converter = new CelsiusConverter();
	}
}

 

posted @ 2018-01-15 13:05  半生戎马,共话桑麻、  阅读(581)  评论(0)    收藏  举报
levels of contents