Question

Objective: Write a Java program that will use a JComboBox from which the user will select...

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

  • Structure your file name and class name on the following pattern:
    • The first three letters of your last name (begin with upper case.).
      • Then the first two letters of your first name (begin with upper case.).
      • Follow this with the name of the program: guiTempConv.
      • For a student called ’John Doe,’ the class name and file name would be: DoeJoGuiTempConv

The program structure and format will be the one used in the videos and supporting material for this chapter.

  • Make sure you have the following comments at the beginning of your program:
/*
 * 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 good comments.
  • Think about the problem and decide what type each of the input numbers should be. Also, think about the calculations and decide what type the variables should be that will hold the results of the calculations.
  • Use camel casing for variable names, and use descriptive variable names. Do not use general variable names like "tax" or "total."
  • Create a JComboBox with two options: Celsius to Fahrenheit and Fahrenheit to Celsius.
  • Use a text field to accept a double that represents the amount of the temperature.
    • Test the user input number to ensure that it is a double.
  • Create two methods for the temperature conversions:
    • Use degreesC = 5(degreesF - 32)/9; for the conversion from Celsius to Fahrenheit.
    • Use degreesF = (9(degreesC)/5) + 32; for the conversion from Fahrenheit to Celsius.
  • Use an un-editable text field to show the converted temperature.
  • Display a label that describes the converted temperature type.
  • Have the cursor come back to the temperature entry field.
  • See the GUI format below.

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

  • An unedtable field is a field that may contain data, but you are not able to edit it. It is basically used to display answers or results of calculations.
  • The field itself is a standard text field.
    -- myTextField = new JTextField(10);
  • The line below makes that field un-editable.
    • myTextField.setEditable(false);
  • You then, of course, have to add it to the panel.
    • panel.add(text2);

Creating the JComboBox

  • In this program you will need to create a JComboBox. You have seen these many times in programs that you have used. They are just one of the many GUI components available in Java.
  • You will create the JComboBox as you have other components that you have already used. The JComboBox, due to its nature, has some specifications to set.
  • Here are the steps to set up the JComboBox:
    • Set a variable for the JComboBox:
      • private JComboBox tempConvert; // Define the JComboBox in the public class.
    • Create a String array of choices for the JComboBox:
      -- String[] convChoices = {"C to F","F to C"}; // Declare an array to hold the choices (in this case only two).
    • Create the JComboBox object:
      • conversionSelector = new JComboBox(convChoices); // Passing the array
      • Add a listener
      • conversionSelector.addActionListener(listen);
    • Then add it to the panel:
      • panel.add(conversionSelector);
    • Later in your logic you will check the selected item:
      • if (conversionSelector.getSelectedItem().toString() == ("C to F"))
      • The "C to F" and "F to C" are simply strings, so you can use whatever labels you want for items in the combo box.

Homework Answers

Answer #1

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.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
I'm new to MIPS. How to write a program that prompts the user for a temperature...
I'm new to MIPS. How to write a program that prompts the user for a temperature in Celsius and then display the result in Fahrenheit. Have to use ineteger to float conversion.
Write a complete Java program which prompts the user of the program to input his/her first...
Write a complete Java program which prompts the user of the program to input his/her first name, then prompts the user for the middle initial and finally prompts the user for the last name. As indicated, there are three prompts to the user. The program should output the user’s name with the first name first, followed by the middle initial, and the last name last, all on one line (with appropriate spacing). If you could also pinpoint exactly where to...
Write Java program Lab51.java which takes in a string from the user, converts it to an...
Write Java program Lab51.java which takes in a string from the user, converts it to an array of characters (char[] word) and calls the method: public static int countVowels(char[]) which returns the number of vowels in word. (You have to write countVowels(char[]) ).
C++ Fahrenheit to Celsius Tables Write a program that first asks the user which Temperature scale...
C++ Fahrenheit to Celsius Tables Write a program that first asks the user which Temperature scale conversion he/she would like to perform: 1. Convert F to C 2. Convert C to F 3. Quit What is your choice? Then it asks the user for input for three real number variables: start_temp, end_temp, temp_incr. It will then produce a two column Fahrenheit to Celsius table or a two column Celsius to Fahrenheit table, depending on the choice. For choice 1, the...
Write a Java program that prompts the user to input a word (String). The program must...
Write a Java program that prompts the user to input a word (String). The program must print the reversed word with all consecutive duplicate characters removed. The program must contain the following classes: - The StackX class (you can use the Java Stack class). - The Reverse class which must contain a private data field called “word” of type string, a constructor, and a void method called revNoDup(). The revNoDup() method must reverse the word and remove the consecutive duplicate...
Download the attached .java file. Run it, become familiar with its processes. Your task is to...
Download the attached .java file. Run it, become familiar with its processes. Your task is to turn TemperatureConversion into GUI based program. it should, at the least, perform similar functions as their text output versions. The key factor to remember is that the workings should remain the same (some tweaks may be necessary) between text and GUI programs, while the means pf visual presentation and user interaction changes. You must properly document, comment, indent, space, and structure both programs. import...
Using Java, write a program that allows the user to play the Rock-Paper-Scissors game against the...
Using Java, write a program that allows the user to play the Rock-Paper-Scissors game against the computer through a user interface. The user will choose to throw Rock, Paper or Scissors and the computer will randomly select between the two. In the game, Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. The program should then reveal the computer's choice and print a statement indicating if the user won, the computer won, or if it was a tie. Allow...
step by step in python please The program will prompt the user as to whether you...
step by step in python please The program will prompt the user as to whether you want to convert from Celsius to Fahrenheit or from Fahrenheit to Celsius Write it so each conversion is contained within its own function (i.e., one function to do the math in one direction, a second to do the math in the other direction) These two functions should just have the input temperature as a parameter and return the output temperature in the other units....
JAVA Write a program that has two functions in which the user chooses which one to...
JAVA Write a program that has two functions in which the user chooses which one to perform; 1. reads in a CSV file of integers into an array and insert it into a binary search tree class 2. deserializes an object and inserts it into a binary search tree class the tree class must be in a separate class from the CSV file read and deserialize object load
Write a program in Java that: 1. will prompt user with a menu that contains options...
Write a program in Java that: 1. will prompt user with a menu that contains options to: a. Add a To-Do Item to a todo list. A To-Do Item contains: i. An arbitrary reference number (4; 44,004; etc.) ii. A text description of the item ("Pick up dry cleaning", etc.) iii. A priority level (1, 2, 3, 4, or 5) b. View an item in the list (based on its reference number) c. Delete an item from the list (based...