简体   繁体   English

如何在JTextField的2个JComboBox中使用值?

[英]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. 我正在尝试做的是创建2个JComboBox和2个JTextField框。 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. 我需要能够编写在第一个JComboBox中使用温度类型(华氏度,摄氏和开尔文)的代码,并将该第一温度类型转换为在第二个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. 必须使用在第一个JTextField框中输入的任何数字(将是所选临时类型的初始值)并将其转换为第二个JTextField框中的新温度类型来完成。 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. 运行测试时,我在第40行收到NullPointerException ,并且我不知道是否正确格式化了if语句中使用的双精度值以使新值再次在第2个JTextField框中显示为String。 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. 在我编写所有其他if语句以处理所有其他情况之前,我正在寻找一些指向到目前为止我是否已完成的指示。

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. 该属性用于该类的其他方法,因此声明String theAttribute需要在构造函数之外。

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(); 另一方面,实例的创建/初始化需要在创建其他字段之后完成,因此在构造函数的末尾, 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 查看ActionListener可以将其添加到字段中,并在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. 当您有两个JComboBox实例时,此示例说明第一个组合中的选择如何更改第二个组合中显示的内容。 For example, selecting Fahrenheit in the first combo would change the second combo's model to display only Celsius or Kelvin . 例如,在第一个组合中选择Fahrenheit将更改第二个组合的模型,以仅显示CelsiusKelvin Etc. 等等。

Addendum: As @Andrew suggests, you'll have to move the initialization for all four instance variables into the constructor. 附录:如@Andrew所建议,您必须将所有四个实例变量的初始化都移到构造函数中。 Here's the main() I used to test your code: 这是我用来测试您的代码的main()

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);
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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