简体   繁体   中英

How do I use the value in 2 JComboBox's in JTextField?

What I am attempting to do is create 2 JComboBox's and 2 JTextField box's. I need to be able to write code that uses the temperature type (Fahrenheit, Celsius, and Kelvin) in the first JComboBox and converts that first temperature type into whichever temperature type has been selected in the 2nd JComboBox. This must be done by using whatever number has been entered into the first JTextField box (that will be the initial value of the selected temp type) and converted into the new temperature type in the 2nd JTextField box. Here is how far I've progressed...

I am getting a NullPointerException at line 40 when I run my test, and I don't know if I have formatted the double used in the if statement correctly to have the new value appear again as a String in the 2nd JTextField box. Before i go through with writing all of the other if statements to handle all of the other scenarios, I am looking for some pointers on if what I have done up till this point is correct.

package temperatureConverter;


import java.awt.FlowLayout;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.JTextField;

public class TempConverter extends JFrame
{
    private JComboBox firstComboBox;
    private JComboBox secondComboBox;
    private JTextField initialTemp;
    private JTextField convertedTemp;
    //private enum TempType { FAHRENHEIT, CELSIUS, KELVIN};
    private static final String[] tempType = { "Fahrenheit", "Celsius", "Kelvin" }; 

    public TempConverter()
    {
        super("Temperature Converter");
        setLayout(new FlowLayout());

        firstComboBox = new JComboBox(tempType);
        firstComboBox.setMaximumRowCount(3);
        firstComboBox.addItemListener(null);
        add(firstComboBox);
        secondComboBox = new JComboBox(tempType);
        secondComboBox.setMaximumRowCount(3);
        secondComboBox.addItemListener(null);
        add(secondComboBox);
        initialTemp = new JTextField ("", 10);
        initialTemp.addActionListener(null);
        add(initialTemp);
        convertedTemp = new JTextField ("", 10);
        convertedTemp.addActionListener(null);
        add(convertedTemp);
    }
    String theInitialTempType = (String) firstComboBox.getSelectedItem();
    String theTempTypeToConvertTo = (String) secondComboBox.getSelectedItem();
    String theChosenTemp = initialTemp.getSelectedText();
    String theNewTemp = convertedTemp.getSelectedText();

    private class textHandler implements ItemListener
    {
        public void itemStateChanged (ItemEvent event)
        {
            double convertedNumberForTheChosenTemp = Double.parseDouble(theChosenTemp);
            double convertedNumberForTheNewTemp = Double.parseDouble(theNewTemp);
            //String string1 = "";
            //String string2 = "";

            if ( theInitialTempType == tempType[0] && theTempTypeToConvertTo == tempType[1] )
            {
                 convertedNumberForTheNewTemp = (convertedNumberForTheChosenTemp   -  32)  *  5 / 9; 
                 String result = String.valueOf(convertedNumberForTheNewTemp);
            }
        }
    }
}
String theInitialTempType = (String) firstComboBox.getSelectedItem();

This code line is outside the constructor where the field is created. The attributes are used in other methods of the class, so the declaration String theAttribute needs to be outside the constructor.

On the other hand, the creation/initialization of the instance needs to be done after other fields are created, so at the end of the constructor, theAttribute = anotherAttribute.getSelectedText();

But even that is not correct. The fields are empty at that stage, so it makes no sense to try calculating results from them. Calculations should be controlled by the end user, and done on action. Look into ActionListener - it can be added to fields and will fire on Enter

As you have two instances of JComboBox , this example shows how a selection in the first combo can change what's shown in the second combo. For example, selecting Fahrenheit in the first combo would change the second combo's model to display only Celsius or Kelvin . Etc.

Addendum: As @Andrew suggests, you'll have to move the initialization for all four instance variables into the constructor. Here's the main() I used to test your code:

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            TempConverter f = new TempConverter();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.pack();
            f.setVisible(true);
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM