When I change the list option in the code below, java picks up my input and gives me an answer that is really weird. This is the code:
package tempconverter;
import javax.swing.*;
import java.awt.event.*;
import java.awt.FlowLayout;
import static java.lang.System.out;
public class TempConverter extends JFrame implements ActionListener {
final static String[] inList = {"From Celsius", "From Fahrenheit", "From Kelvin"};
static JFrame f = new JFrame();
static JTextField enter = new JTextField(3);
static JButton confirm = new JButton("Convert");
static JList choose = new JList(inList);
public static void main(String[] args) {
confirm.addActionListener(new TempConverter());
f.setLayout(new FlowLayout());
f.setSize(300, 60);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(enter);
f.add(confirm);
f.add(choose);
f.setVisible(true);
}
@Override
public void actionPerformed (ActionEvent e) {
Object choice = choose.getSelectedValue();
double toConvert = Double.parseDouble(enter.getText());
double inF, inK, inC;
if (choice.equals("From Celsius")) {
inF = toConvert * 1.8 + 32;
inK = toConvert + 273.15;
out.println("In degrees Fahrenheit, " + toConvert + " degrees Celsius would be " + inF + " degrees.");
out.println("In degrees Kelvin, " + toConvert + " degrees Celsius would be " + inK + " degrees.");
}
if (choice.equals("From Fahrenheit")) {
inC = toConvert - 32 / 1.8;
inK = toConvert - 32 / 1.8 - 273.15;
out.println("In degrees Celsius, " + toConvert + " degrees Fahrenheit would be " + inC + " degrees.");
out.println("In degrees Kelvin, " + toConvert + " degrees Fahrenheit would be " + inK + " degrees.");
}
if (choice.equals("From Kelvin")) {
inC = toConvert - 273.15;
inF = inC + 1.8 + 32;
out.println("In degrees Celsius, " + toConvert + " degrees Kelvin would be " + inC + " degrees.");
out.println("In degrees Fahrenheit, " + toConvert + " degrees Kelvin would be " + inF + " degrees.");
}
}
}
How do I make java realise that I changed the list selection? An example I tested is that I set the selection to "From Fahrenheit" and typed 32, but it gave me 14.222222222222221 degrees Celsius and -258.92777777777775 degrees Kelvin.