Convert Temperature

To convert the temperature, we have created two textField for Fahrenheit value and Celsius value.

Convert Temperature


This section illustrates you how to convert the temperature from Fahrenheit to Celsius.

To convert the temperature, we have created two textField for Fahrenheit value and Celsius value. A button is created to perform an action. As the user enters the Fahrenheit value, and click the button, the temperature in Fahrenheit has been converted into Celsius and displayed on the specified textfield.

The method fahrenheitText.getText() get the text value of Fahrenheit temperature and passed the value to the variable selected of String type. 

Following code converts temperature from F to C:

double f = Double.parseDouble(selected);
double c = (f - 32) / 1.8;

The method Double.parseDouble(selected) returns a double value represented by the specified String. The method Double.toString(c) returns the string representation of double argument. 

Here is the code of

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TemperatureConverterInSwing implements ActionListener {

JFrame frame;
JPanel panel;
JTextField fahrenheitText;
JLabel celLabel, fahLabel;
JButton changeTemp;
JTextField celciusText;

public TemperatureConverterInSwing() {
  frame = new JFrame("Change Celsius to Fahrenheit");
  frame.setSize(new Dimension(18080));

  panel = new JPanel(new GridLayout(32));
  frame.getContentPane().add(panel, BorderLayout.CENTER);
private void addItems() {
  fahLabel = new JLabel("Fahrenheit", SwingConstants.LEFT);
  fahrenheitText = new JTextField(20);
  changeTemp = new JButton("Convert");
  celLabel = new JLabel("Celcius", SwingConstants.LEFT);
  celciusText = new JTextField(20);
  panel=new JPanel(new GridLayout(4,1));
public void actionPerformed(ActionEvent event) {
 String selected=fahrenheitText.getText();
 if (selected.equals("")){
  System.out.println("enter the fahrenheit value");
  JOptionPane.showMessageDialog(null,"Enter the fahrenheit value");
  double f = Double.parseDouble(selected);
  double c = (f - 32) / 1.8;
private static void createAndShowGUI() {
TemperatureConverterInSwing converter = new TemperatureConverterInSwing();
public static void main(String[] args) {
  javax.swing.SwingUtilities.invokeLater(new Runnable() {
  public void run() {

Output will be displayed as:

Download Source Code

Share on Google+Share on Google+

Convert Temperature

Posted on: October 14, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Convert Temperature   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image