我试图做的是创建 2 个 JComboBox 和 2 个 JTextField 框。我需要能够编写在第一个 JComboBox 中使用温度类型(华氏、摄氏和开尔文)的代码,并将第一个温度类型转换为在第二个 JComboBox 中选择的任何温度类型。这必须通过使用在第一个 JTextField 框中输入的任何数字(这将是所选温度类型的初始值)并在第二个 JTextField 框中转换为新的温度类型来完成。这是我进步的程度...
当我运行我的测试时,我在第 40 行得到一个NullPointerException
,我不知道我是否正确格式化了 if 语句中使用的双精度,以使新值在第二个 JTextField 框中再次显示为字符串。在我编写所有其他 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);
}
}
}
}