user2971033
user2971033

Reputation:

GUI - JFrame: declaring variables

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?

Upvotes: 0

Views: 5342

Answers (3)

user3150201
user3150201

Reputation: 1947

In Java, and pretty sure in programming in general, there are 'references', and objects.

When creating an object, you usually create a reference to it. You use the reference to access that object later.

enter image description here

obj is a reference of type Object to that new object you created.

You can't simply write Object obj;, because that would be only declaring a reference. You have to "attach" an object to that reference, and than you can use it, because it leads somewhere.

Hope this helps you

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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.,

public class MyFoo {
    private String fooString;  // (A)

    public MyFoo() {
      fooString = "hello world";  // (B)
    }

You could also declare it and initialize it on the same line.

public class MyFoo {
    private String fooString = "hello world";
    private JTextField textField = new JTextField(10);

    public MyFoo() {
      // now can use both variables
    }

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.

Upvotes: 4

BitNinja
BitNinja

Reputation: 1487

Declaring and initializing are two different things. You could declare and initialize them all at once like this:

private JTextField item1 = new JTextField(10);
private JTextField item2 = new JTextField(10);
private JTextField item3 = new JTextField(10);
add(item1);
add(item2);
add(item3);

Upvotes: 1

Related Questions