I'm trying to use an input from JTextField and turn it into double 'coz I'm gonna use the input in a mathematical formula in my program.. but when I try to run the codes, it gives an error.. I think I got the wrong way of parsing.. ANY HELP? Thanks!
xLabel = new JLabel("Subject");
xTF = new JTextField(4);
xTF.addKeyListener(new KeyHandler());
xString = xTF.getText();
xDouble = Double.parseDouble(xString);
KeyListener
on text components, use a DocumentFilter
, take a look at Implementing a Document Filter and DocumentFilter Examples for more details InputVerifier
instead. See Validating Input for more details JFormmattedField
or JSpinner
instead. See How to Use Formatted Text Fields and How to Use Spinners for more details It's difficult to tell, but remember, you're operating in an event driven environment, until the user does something, you should not be trying to get the value of a field
Remove any whitespace available by using trim() on the string
xDouble = Double.parseDouble(xString.trim());
Where i'm assuming xString is a valid String and xDouble is of type Double
You should use parseDouble(String s)
and exception which is related is NumberFormatException
The java.lang.Double.parseDouble() method returns a new double initialized to the value represented by the specified String, as done by the valueOf method of class Double.
For example:
public class Main {
public static void main(String[] args) {
String str = "50.00001";
double retval =Double.parseDouble(str);
System.out.println("Value = " + retval);
}
}
That looks fine, did you type in the right values in your textfield before you tested it? Per example if you leave it empty or type in "1,3" it wouldn't probably accept it.
Edited: I just did a test and as I said, it only accepts values like this: "1.3"
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class MyApp extends JFrame implements ActionListener {
JTextField textField;
JLabel label;
JButton okButton;
public MyApp() {
textField = new JTextField(4);
label = new JLabel("N/A");
okButton = new JButton("Ok");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout());
add(textField, BorderLayout.NORTH);
add(label, BorderLayout.CENTER);
add(okButton, BorderLayout.SOUTH);
okButton.addActionListener(this);
pack();
}
public static void main(String[] args) {
MyApp app = new MyApp();
app.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == okButton) {
double d = 0;
d = Double.parseDouble(textField.getText());
label.setText(String.valueOf(d));
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.