0

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?

4

3 回答 3

4

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.

于 2014-01-27T21:13:28.490 回答
1

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);
于 2014-01-27T21:14:54.980 回答
0

在 Java 中,并且在一般编程中非常确定,有“引用”和对象。

创建对象时,通常会创建对它的引用。您稍后使用该引用访问该对象。

在此处输入图像描述

obj是对Object您创建的新对象的类型引用。

你不能简单地写Object obj;,因为那只是声明一个引用。您必须将一个对象“附加”到该引用,然后才能使用它,因为它指向某个地方。

希望这可以帮助你

于 2014-01-27T21:48:34.383 回答