企业成本管理案例:如何在以下程序中加一个“取消”按钮啊?

来源:百度文库 编辑:查人人中国名人网 时间:2024/05/08 00:03:20
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CelsiusConverter2 implements ActionListener {
JFrame converterFrame;
JPanel converterPanel;
JTextField tempCelsius;
JLabel celsiusLabel,fahrenheitLabel;
JButton convertTemp;
//构造函数
public CelsiusConverter2() {
//创建容器
converterFrame = new JFrame("华氏温度转换成摄氏温度");
converterFrame.setSize(40, 40);
converterPanel = new JPanel();
converterPanel.setLayout(new GridLayout(3, 3));
//增加widgets
addWidgets();
//向frame中添加panel
converterFrame.getContentPane().add(converterPanel,BorderLayout.CENTER);
//关闭窗口时退出
converterFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//显示转换器
converterFrame.pack();
converterFrame.setVisible(true);
}
//为转换器创建和增加widgets
private void addWidgets(){
//创建widgets.
convertTemp = new JButton("确定" );
tempCelsius = new JTextField(2);
celsiusLabel = new JLabel("摄氏温度",SwingConstants.LEFT);
fahrenheitLabel = new JLabel("华氏温度",SwingConstants.LEFT);
celsiusLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
fahrenheitLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
//监听按钮触发事件
convertTemp.addActionListener(this);
//将widgets添加到转换器中
converterPanel.add(tempCelsius);
converterPanel.add(celsiusLabel);
converterPanel.add(convertTemp);
converterPanel.add(fahrenheitLabel);
}
//实现ActionListener接口
public void actionPerformed(ActionEvent event) {
//将摄氏温度转换为双精度小数,并且转换为华氏温度
int tempFahr =
(int)((Double.parseDouble(tempCelsius.getText())) * 1.8 + 32);
//将所得结果赋给fahrenheitLabel标签,并且根据温度值设置字体颜色
if (tempFahr<=32){
fahrenheitLabel.setText("<html><Font Color=blue>"+tempFahr+
"°</Font><Font Color=black>华氏温度</Font><html>");
}else if (tempFahr <=80) {
fahrenheitLabel.setText("<html><Font Color=green>"+tempFahr+
"°</Font><Font Color=black>华氏温度</Font><html>");
} else {
fahrenheitLabel.setText("<html><Font Color=red>"+tempFahr+
"°</Font><Font Color=black>华氏温度</Font><html>");
}
}
//main方法
public static void main(String[]args){
//设置显示风格
try{
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
}
catch(Exception e){}
CelsiusConverter2 converter = new CelsiusConverter2();
}
}

在JButton convertTemp;后面加上
JButton btnCancel;

convertTemp = new JButton("确定" ); 加上
btnCancel=new JButton("取消");

converterPanel.add(convertTemp); 加上
converterPanel.add(btnCancel);加到面板上去

你也可以给这个按钮加上监听事件.