To get a number from a JTextField, I suggest adding an ActionListener to it, just like you would to a JButton. Keep in mind that this requires pressing Enter.
If you wish to convert as soon as the user stops typing, a clean way of doing this would be adding a FocusListener to the text field and implementing the focusLost method to call the conversion method. This will convert the units when the text field component loses focus (e.g. when you click on something else).
As far as the combo boxes go, they also work with ActionListeners — whenever a user selects an option, the listener is triggered. This, of course, means that you can do something along the lines of this:
Got the JComboBox updater working, but now it's not executing the method f2c. Enumerators are out of the question due to class assignment. Been working on it since last week and it's due tomorrow sometime and all that.
package tempconv;
import javax.swing.*;
import java.awt.event.*;
public class Tempconv {
// FAHRENHEIT
static double f2c(double temp) { // Fahrenheit/Imperial to Celsius/Metric (°F-°C)
return (5/9)*(temp-32); }
static double f2k(double temp) { // Fahrenheit/Imperial to Kelvin (°F-°K)
return (temp + 459.67) * (5/9); }
// CENTIGRADES
static double c2f(double temp) { // Celsius/Metric to Fahrenheit/Imperial (°C-°F)
return temp * (9/5) + 32; }
static double c2k(double temp) { // Celsius/Metric to Kelvin (°C-°K)
return temp+273.15; }
// KELVIN
static double k2f(double temp) { // Kelvin to Fahrenheit/Imperial (°K-°F)
return temp * (9/5) - 459.67; }
static double k2c(double temp) { // Kelvin to Celsius/Metric (°K-°C)
return temp - 273.15; }
static void check(double temp, String from, String to) {
final ui frame = new ui();
if (from.equals("°F") && to.equals("°C")) {
//double buff = Double.parseDouble(frame.txt_Temp.getText());
frame.l_result.setText(Double.toString(f2c(temp))); }
}
public static void main(String[] args) {
// Let's set up some frame properties here, first.
final ui frame = new ui();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(275, 85);
frame.setResizable(false);
frame.cb_fromunit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
}
});
frame.cb_tounit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
// Set your unit field or w/e you have to comboBoxUnits.getSelectedItem(), then call the conversion method.
// DO WHATEVER on this line, preferrably run temp. conversion
//double temp = Double.parseDouble(frame.txt_Temp.getText());
//frame.l_result.setText(Double.toString(f2c(temp)));
Object from = frame.cb_fromunit.getSelectedItem();
Object to = frame.cb_tounit.getSelectedItem();
check(Double.parseDouble(frame.txt_Temp.getText()), from.toString(), from.toString());
}
});
}}