0

Im pretty sure this it is possible but im trying to declare multiple instances of the JTextField class on one line, rather than declaring them all on a separate lines for example.

JTextField field1 = new JTextField();
JTextField field2 = new JTextField();
JTextField field3 = new JTextField();
JTextField field4 = new JTextField();
JTextField field5 = new JTextField();

Im positive i have done this before but it has escaped me. I would like if possible to have something like f1, f2, f3, f4 = new JTextField();

Is it possible to declare them on a single line or am i imagining things

The suggested answer saying its repeated isnt correct, what the suggest answer is saying is not what im looking for. The suggested answers dont work with JTextField on a single line only. The ones suggest do state the same type of same value, i want same type with differing values.

  • 2
    You can use `JTextField field1 = new JTextField(), field2 = new JTextField,...;`, but why should you? The way you did is is much more readable. – Turing85 Apr 18 '15 at 19:57
  • Cannot get it to work from that individual question, it works for string but cant get it to work for JTextField() That question seems to point all variables to the same value doesnt it? –  Apr 18 '15 at 20:00
  • The closest thing I can think of to a working solution is if had you all of these fields in an array, then you could use a 1 line loop to initialize all of them. – Shar1er80 Apr 18 '15 at 20:40

1 Answers1

2

You should have Googled this question and you should have found this answer Initializing multiple variables to the same value in Java

or

Java one line variable declaration?

Edit

JTextField field1, field2, field3;

But they will be initialize to null and you will need to assign them later

or

JTextField field1 = new JTextField(), field2 = new JTextField();

but there it's less readable and not a good practice

Community
  • 1
  • 1
user43968
  • 2,049
  • 20
  • 37
  • 2
    This shouldn't be an answer. It should have been a flag as a duplicate on the OP. – RealSkeptic Apr 18 '15 at 20:01
  • Thats still not really what im looking for, im positive i can have it like i would for say an int int a, b, c, d; and then declare them a bit later, but i want to have this with JTextFields, i cant seem to remember how i would get them one a single line like above. –  Apr 18 '15 at 20:05
  • check the edit JTextField is just a type like int, double, string ... – user43968 Apr 18 '15 at 20:07