In the following code I have created 3 variables:
public class tuna extends JFrame {
//Creating 3 text fields
private JTextField item1;
private JTextField item2;
private JTextField item3;
what I dont understand is why I then need to do the following:
item1=new JTextField(10);
add(item1);
Why is it necessary to declare item1 as a jtextfield again? Is it solely to create its size and text etc?
You're not declaring it again. You're initializing it with the second bit of code -- big difference.
This is no different from any other reference variable. i.e.,
You could also declare it and initialize it on the same line.
So the first statement (statement (A) in my String example above) in your code creates variable of type JTextField, but when created they are automatically filled with default values, which for reference variables (everything except for primitives such as ints, doubles, floats,...) is
null
. So you have variables that refer to null or nothing, and before using them you must assign to them a valid reference or object, and that's what your second bit of code does (statement (B) in my String example above) .You will want to run, not walk to your nearest introduction to Java tutorial or textbook and read up on variable declaration and initialization as you really need to understand this very core basic concept before trying to create Swing GUI's, or any Java program for that matter. It's just that important.