【发布时间】:2017-12-20 04:53:24
【问题描述】:
我对 Java 非常陌生,正在学习 Java 1 课程。我试图在 if 语句中使用 JComboBox 选择,然后根据 JTextField 中的选择显示答案。这一切都正确编译,但答案不会显示,我不知道我需要改变什么。我已经搜索并尝试了几种不同的方法,但似乎都没有。
import javax.swing.*;
import java.awt.event.*;
public class HayDyGuiTempConv extends JFrame
{
public static void main(String[] args)
{
new HayDyGuiTempConv();
}
private JButton buttonConvert;
private JButton exitButton;
private JTextField textAmount;
private String fieldText;
private JTextField field;
public HayDyGuiTempConv()
{
this.setSize(440,150);
this.setLocation(350,420);
this.setTitle("Temperature Conversion");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ButtonListener bl = new ButtonListener();
JPanel panel1 = new JPanel();
panel1.add(new JLabel("Enter temperature to convert: "));
textAmount = new JTextField(6);
panel1.add(textAmount);
JComboBox<String> comboBox = new JComboBox<> (new String[] {"C to F", "F to C"});
comboBox.addActionListener(bl);
panel1.add(comboBox);
buttonConvert = new JButton("Convert");
buttonConvert.addActionListener(bl);
buttonConvert.setToolTipText("Convert the temperature.");
panel1.add(buttonConvert);
panel1.add(new JLabel("Temp: "));
field = new JTextField(6);
field.setEditable(false);
panel1.add(field);
exitButton = new JButton("Exit");
exitButton.addActionListener(bl);
exitButton.setToolTipText("Exit the program.");
panel1.add(exitButton);
this.add(panel1);
this.setVisible(true);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == buttonConvert)
{
if(e.getSource() == ("C to F"))
{
double tempEntered = Double.parseDouble(textAmount.getText());
double tempConverted = tempEntered - 32 * (5/9);
String tempAmount = (Double.toString(tempConverted));
field.setText(tempAmount);
}
else if(e.getSource() == ("F to C"))
{
double tempEntered = Double.parseDouble(textAmount.getText());
double tempConverted = tempEntered * (9/5) + 32;
String tempAmount = (String.format("%.2f",(tempConverted)));
field.setText(tempAmount);
}
}
else if(e.getSource() == exitButton)
{
System.exit(0);
}
}
}
}
编辑:当我输入一个数字并尝试转换时,我尝试了这两个建议并尝试转换我在交互窗格中得到这个:线程“AWT-EventQueue-0”中的异常java.lang.ClassCastException:javax。 swing.JButton 不能转换为 javax.swing.JComboBox
【问题讨论】:
标签: java swing if-statement jtextfield jcombobox