编写动作侦听器以关闭程序java

时间:2015-11-08 18:22:59

标签: java swing actionlistener

我编写了将华氏温度转换为摄氏温度的代码。单击窗口右上角的X时,我的动作监听器没有关闭程序。任何指导表示赞赏。似乎主类没有识别defaultcloseopertion的代码。

 import java.awt.*;
import java.awt.event.*;

public class TemperatureConversion extends Frame implements ActionListener
{
    private final Label lblInput;
    private final Label lblOutput;
    private final TextField tfInput;
    private final TextField tfOutput;
    private double farenheit;
    private double celcius;

    public TemperatureConversion()
    {
        setLayout(new FlowLayout());



        lblInput = new Label ("Enter degrees in Farenheit: ");
        add(lblInput);

        tfInput = new TextField(10);
        add(tfInput);
        tfInput.addActionListener(this);


        lblOutput = new Label("Degrees in celcius:");
        add(lblOutput);

        tfOutput = new TextField(10);
        tfOutput.setEditable(false);
        add(tfOutput);

        setTitle("Farenheit to Celcius Conversion");
        setSize(350, 120);
        setVisible(true);
    }



    @Override
    public void actionPerformed(ActionEvent e) {
        farenheit = Integer.parseInt(tfInput.getText());
        celcius = (5.0/9)*(farenheit -32);
        tfInput.setText("");
        tfOutput.setText(celcius + "");


    }
}

第二个文件包括主要类

import javax.swing.JFrame;

public class TemperatureConversionTest {

    public static void main(String[] args)
    {
        TemperatureConversion textFieldFrame = new TemperatureConversion();
        textFieldFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        textFieldFrame.setSize(350, 100);
        textFieldFrame.setVisible(true);
    }
}

2 个答案:

答案 0 :(得分:5)

setDefaultCloseOperationJFrame而非java.awt.Frame

的成员方法
public class TemperatureConversion extends JFrame implements ActionListener

答案 1 :(得分:3)

您需要在setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 方法之后调用以下方法。

swing

这需要在JFrame中明确完成。您需要解决的另一件事是更改类签名以扩展Frame而不是Frame。由于awtJFrame库,public class TemperatureConversion extends JFrame implements ActionListener 来自摇摆。

<version>0.98.4-hadoop2</version>