In: Computer Science
Question 2: Create a very simple temperature converter form having two text fields. The first one is where the user will enter temperature. The second field is where the computed temperature value is displayed depending on the unit (F or C).
Things to consider:
Please refer to the comments of the program for more clarity.
// Importing required packages
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// Extending the JFrame for adding the text fields
public class TempConversion extends JFrame
{
// initializing the constants
private static final int WINDOW_WIDTH = 500;
private static final int HEIGHT = 80;
private static final double far_to_c = 5.0/9.0;
private static final double c_to_far = 9.0/5.0;
private static final int Factor = 32;
// initializing the labels
private JLabel cLabel;
private JLabel fLabel;
// initializing the text fields
private JTextField cTF;
private JTextField fTF;
// // initializing the handlers
private CHandler cHandler;
private FHandler fHandler;
// Function to convert the Celsius to Fahrenheit and vice versa
public TempConversion()
{
// Setting the title
setTitle("Temperature Converter");
Container c = getContentPane();
// Setting the layout
c.setLayout(new GridLayout(1,4));
// Providing values to the labels
cLabel = new JLabel("Temp in C: ",
SwingConstants.RIGHT);
fLabel = new JLabel("Temp in F: ",
SwingConstants.RIGHT);
// Defining the size of the text field
cTF = new JTextField(7);
fTF = new JTextField(7);
// Adding the components to the container
c.add(cLabel);
c.add(cTF);
c.add(fLabel);
c.add(fTF);
// Initializing the handlers
cHandler = new CHandler();
fHandler = new FHandler();
cTF.addActionListener(cHandler);
fTF.addActionListener(fHandler);
// Setting the windows size
setSize (WINDOW_WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
// Handler implementing the Action Listener
private class CHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double c, f;
// Logic of the conversion
c = Double.parseDouble(cTF.getText());
f = c * c_to_far + Factor;
fTF.setText(String.format("%.2f", f));
}
}
// Handler for Fahrenheit implementing the Action Listener
private class FHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double c, f;
// Logic for conversion
f = Double.parseDouble(fTF.getText());
c = (f - Factor) * far_to_c;
cTF.setText(String.format("%.2f", c));
}
}
// Main method or the starting point of the program.
public static void main(String[] args)
{
TempConversion t = new TempConversion();
t.setLocationRelativeTo(null);
}
}
Sample Input-Output/CodeRun - 1:
Sample Input-Output/CodeRun - 2:
Please let me know in the comments in case of any confusion. Also, please upvote if you like.