I'm attempting to make an application for a small game, and I'm currently having an issue of getting my code to work. It should be displaying a window with a text field, a jbutton, and an uneditable text field. I need to get it to read what I put into the first text field. However when I run it all I receive is this:
Exception in thread "main" java.lang.NumberFormatException: For input
string: "Enter Command"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.parseDouble(Double.java:510)
at TextAdv.<init>(TextAdv.java:16)
at TextAdv.main(TextAdv.java:43)
I'm not exactly great at reading errors and I've been trying to figure this out for an hour or so. If someone could please help me fix this issue, it would be greatly appreciated. Thank you.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextAdv {
JFrame jtfMainFrame;
JButton jbnButton2;
JTextField jtfInput, jtfCommand;
JPanel jplPanel, jplPanel2;
public TextAdv() {
jtfMainFrame = new JFrame("TextAdv");
jbnButton2 = new JButton("Quit (LEAVES GAME)");
jtfInput = new JTextField(55);
jtfCommand = new JTextField("Enter Command", 40);
double command = Double.parseDouble(jtfCommand.getText());
jplPanel = new JPanel();
jplPanel2 = new JPanel();
jbnButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
jtfInput.setEditable(false);
jplPanel.setLayout(new FlowLayout());
jplPanel.add(jtfCommand);
jplPanel.add(jbnButton2);
jplPanel2.add(jtfInput);
jtfMainFrame.getContentPane().add(jplPanel2, BorderLayout.SOUTH);
jtfMainFrame.getContentPane().add(jplPanel, BorderLayout.CENTER);
jtfMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtfMainFrame.pack();
jtfMainFrame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager
.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
}
TextAdv application = new TextAdv();
}
}
You are trying to parse value of the jtfCommand
field which is "Enter Command"
:
double command = Double.parseDouble(jtfCommand.getText());
This line throws NumberFormatException
if jtfCommand.getText()
returns a String that is not a number.
You should be aware that the following line of code creates JTextField
instance with the text value initialized to the first argument (Source Code ):
jtfCommand = new JTextField("Enter Command", 40);
And when you are calling jtfCommand.getText()
it returns "Enter Command"
that is obviously not a number.