Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write Action Listener to close program java

I have written code to convert Fahrenheit to Celsius. My action listener is not closing the program when clicking on the X in the top right of the window. Any guidance is appreciated. It seems the main class is not recognizing the code for the 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 + "");


    }
}

2nd file includes main class

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);
    }
}
like image 791
CVYC CVYC Avatar asked May 02 '26 13:05

CVYC CVYC


2 Answers

setDefaultCloseOperation is a member method of JFrame not java.awt.Frame

public class TemperatureConversion extends JFrame implements ActionListener
like image 140
Reimeus Avatar answered May 04 '26 03:05

Reimeus


You need to call the below method after the setVisible(true); method.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this needs to be done explicitly in swing. One more thing that you need to address would be change the class signature to extend JFrame instead of Frame. Since, Frame is an awt library where as JFrame comes from swing.

public class TemperatureConversion extends JFrame implements ActionListener
like image 36
Vivek Singh Avatar answered May 04 '26 03:05

Vivek Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!