user1183685
user1183685

Reputation: 11

Getting user input by JTextField in Java?

I am trying to get user inputs from a textbox so I can take the user input to calculate the displacement for a ball.

I tried this

double initialvelocity = new JTextBox("enter your initial velocity");

so I have a variable with data that I can use. I just cant get it to work and this has been a obstacle to my first proper java project.

Could anyone suggest how I can get a variable to store data using JTextField or is there other alternatives?

Upvotes: 1

Views: 76516

Answers (4)

user684934
user684934

Reputation:

A JTextField should be stored like this:

JTextField v0TextField = new JTextField ("initial velocity");

And when you want to access the current string in the text box:

String strV0TextBox = v0TextField.getText();

Then you'll want to parse this into a double:

double initialvelocity = Double.parseDouble(strV0TextField);

Upvotes: 9

sinemetu1
sinemetu1

Reputation: 1726

See this tutorial for using a jTextField here.

You want to instantiate the box like:

    JTextField myTextField = new JTextField("enter your initial velocity");

    //Probably should do some kind of validation on the input if you only want numbers
    //get The Text and parse it as a double
    double initVelocity = Double.parseDouble(myTextField.getText());

Upvotes: 2

Garrett Hall
Garrett Hall

Reputation: 30022

If you just want to get input from the user the easiest way is to use a dialog:

double value = Double.parseDouble(
           JOptionPane.showInputDialog("please enter value"));

Upvotes: 4

RanRag
RanRag

Reputation: 49537

The correct way to use JTextField is

JTextField box = new JTextField(" Enter Initial Velocity");
String velocity_str = box.getText();

Than parse into a double

double initialvelocity = Double.parseDouble(velocity_str);

Upvotes: 3

Related Questions