Objective:
Write a Java program that will use a JComboBox from which the user will select to convert a temperature from either Celsius to Fahrenheit, or Fahrenheit to Celsius. The user will enter a temperature in a text field from which the conversion calculation will be made. The converted temperature will be displayed in an uneditable text field with an appropriate label.
Specifications
The program structure and format will be the one used in the videos and supporting material for this chapter.
/* * Program Name: The program name. * Author: Your first and last name. * Date Written: The current date. * The class name: CIT 149 Java 1 * Description: Meaningful description of the purpose of the program. */
Use parseDouble to convert the input to a double for use in the calculation.
use an inner class for the listener.
Creating the Un-editable Text Field
Creating the JComboBox
Java program to implement the above functionality is :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GuiTempConv {
static JFrame f;
static JLabel label;
static JComboBox conversionSelector;
static JTextField result,input;
public static void main(String[] args)
{
f = new JFrame("frame");
String[] s = {"C to F","F to C"};
GuiTempConv g = new GuiTempConv();
ConvertTemperature c = g.new ConvertTemperature();
conversionSelector = new JComboBox(s);
conversionSelector.addActionListener(c);
input = new JTextField(8);
result = new JTextField(8);
result.setText("");
result.setEditable(false);
label = new JLabel("F");
JPanel p = new JPanel();
p.add(input);
p.add(label);
p.add(conversionSelector);
p.add(result);
p.add(label);
f.add(p);
f.setSize(400, 400);
f.show();
}
public static double fahrenheittoCelsius(double temp){
return 5 * (temp - 32)/9;
}
public static double celsiustoFahrenheit(double temp){
return (9 * (temp)/5) + 32;
}
private class ConvertTemperature implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if(input.getText() != null){
double temp = Double.parseDouble(input.getText());
double res=0;
if(conversionSelector.getSelectedItem().toString()=="C to F"){
res=celsiustoFahrenheit(temp);
label.setText("F");
}else{
res=fahrenheittoCelsius(temp);
label.setText("C");
}
result.setText(res+"");
}
}
}
}
The output screenshots are as below:
If you have any queries regarding this answer, please reach out through the comment section.
Get Answers For Free
Most questions answered within 1 hours.