Can I pass a variable to a TextField in Java?

Soldato
Joined
12 Sep 2003
Posts
11,215
Location
Newcastle, UK
Hello. :)

I'm nearly finished my little project for Uni, however, I am stuck on the very last part. I have some text boxes and for one I would like to have in the box a variable. The variable is always different so I can't "hard code" an answer into the field.

Here is the small code for the text box:-

Code:
tb5 = new TextField("Time: ","",20,TextField.ANY);

Now the part where the two " " are, I can enter words etc etc and they will show in the box. However, is it possible to say put a variable somehow into there?

Code:
tb5 = new TextField("Time: ","+TEST_VALUE+",20,TextField.ANY);

TEST_VALUE = "whatever I want";

Basically I'm passing a time to this textfield, and the time will always be different depending on when it was stopped. :) At the moment I'm struggling, as it's taken everything I enter as a STRING and so just outputting it in the box.

Thanks for any suggestions... again! ;)
 
Welshy said:
toString()?

Nearly, I just did the following...

Code:
//PUT THIS AT THE START

TEST_VALUE="Hello";

//THEN FURTHER DOWN IS THIS

tb5 = new TextField("Time: ",TEST_VALUE,20,TextField.ANY);

Lol and then it works, it outputs "Hello" in the box. I'm trying to now get the contents of a StringBuffer out and into the textbox, which is using that .toString() part like you say. :p
 
Could you not just have made a string variable, and then pass that into the constructor? :confused:

I'm probably just missunderstanding you, goodluck with it :)
 
String value = "whatever";
tb5 = new TextField("Time: " + value ,20,TextField.ANY);

I guess this is what your trying to do?
 
There is an easier way.

Code:
tb5 = new JTextField(20);
TEST_VALUE = "whatever I want";
tb5.setText("Time: "+TEST_VALUE);
 
Didn't relise you were using J2ME. This would be the way of doing it:

Code:
String TEST_VALUE = "whatever I want";
tb5 = new TextField("Time: "+"",20,TextField.ANY);
tb5.setString(TEST_VALUE)

The other way is the same but you don't need setString() as you are giving it a variable in it's initialisation.
 
Last edited:
Back
Top Bottom