Java Swing – Fahrenheit to Celsius Conversion Application


Introduction


This Java Swing Program helps to convert Fahrenheit to Celsius.
The user has to enter the Fahrenheit and hit the enter button to allow the program to convert to Celsius.

 


Program Code


KWFahrenheitApp.java

 

package com.kw.javaswing;

import javax.swing.JFrame;

/**
* This class helps generate Fahrenheit to Celsius Conversion Application.
*
* @author dsahu1
*
*/
public class KWFahrenheitApp {

/**
* This main method used to execute program.
*
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Fahrenheit Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Instantiate Panel
KWFahrenheitPanel panel = new KWFahrenheitPanel();
// Add Panel to Frame
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}

 


KWFahrenheitPanel.java

 

package com.kw.javaswing;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
* This class helps to generate Panel.
*
* @author dsahu1
*
*/
public class KWFahrenheitPanel extends JPanel {

private static final long serialVersionUID = 1000000L;
private JLabel inputLabel, outputLabel, resultLabel;
private JTextField fahrenheit;

public KWFahrenheitPanel() {
// Instantiate Labels and Text Button
inputLabel = new JLabel("Enter temperature in Fahrenheit:");
outputLabel = new JLabel("Temperature in Celsius: ");
resultLabel = new JLabel("---");
fahrenheit = new JTextField(5);
fahrenheit.addActionListener(new ConversionListener());
add(inputLabel);
add(fahrenheit);
add(outputLabel);
add(resultLabel);
setPreferredSize(new Dimension(300, 120));
setBackground(Color.yellow);
}

/**
* This Listener helps to convert Fahrenheit to Celsius.
*
* @author dsahu1
*
*/
private class ConversionListener implements ActionListener {

public void actionPerformed(ActionEvent event) {
int fahrenheitTemp, celsiusTemp;
String text = fahrenheit.getText();
fahrenheitTemp = Integer.parseInt(text);
// Calculation Logic
celsiusTemp = (fahrenheitTemp - 32) * 5 / 9;
resultLabel.setText(Integer.toString(celsiusTemp));
}
}
}

 


Program Execution


  • The user can execute this program using the eclipse. Right Click on the program KWFahrenheitApp.java and click on Run – > Java Application

 

  • Above Steps navigates to Application Home Page.

 

  • Enter the Fahrenheit in the text box and hit the enter button.


 

Leave a Reply

Your email address will not be published. Required fields are marked *