[英]Why can I not call a public method of a created object?
When I am trying to run this Java program to make a JTextField: 当我尝试运行此Java程序以创建JTextField时:
import java.awt.*;
import javax.swing.*;
public class TextField1 extends JFrame{
private final int WIDTH = 320;
private final int HEIGHT = 250;
private FlowLayout flow = new FlowLayout();
private JTextField myOutput = new JTextField();
public TextField1() {
super("My TextField Example");
setSize(WIDTH, HEIGHT);
setLayout(flow);
JTextField myOutput = new JTextField(20);
add(myOutput);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void createGUI(){
myOutput.setText("I am a text field showing output!");
myOutput.setEditable(false);
}
public static void main(String[]args) {
TextField1 myTextField = new TextField1();
myTextField.createGUI();
System.out.println(myTextField.myOutput.getText());
}
}
It seems as if it does not register the createGUI() method. 似乎它没有注册createGUI()方法。 Can you explain why this is? 你能解释为什么吗?
Inside the constructor, you are creating a new variable called myOutput
, which is not the same as the instance variable declared above. 在构造函数内部,您正在创建一个名为myOutput
的新变量,该变量与上面声明的实例变量不同。 JTextField myOutput
should be myOutput
JTextField myOutput
应该是myOutput
EDIT: 编辑:
You declare a method-local variable myOutput
and add it to your frame. 您声明一个方法局部变量myOutput
并将其添加到框架中。 createGUI()
uses the instance variable declared at the top of the class, therefore it does not affect the TextField
in the frame. createGUI()
使用在类顶部声明的实例变量,因此它不会影响框架中的TextField
。
I am just extending the answer which was provided by blueygh2. 我只是在扩展blueygh2提供的答案。 The main problem is that : 主要的问题是:
you have not given the size of the JTextField in the class which will be 0 by default 您没有在类中给定JTextField的大小,默认情况下将为0
private JTextField myOutput = new JTextField();//no size specified
Also in constructor you are Declaring another JTextField with same name that will be eligible for Garbage collection after Object Creation : 同样在构造函数中,您正在声明另一个具有相同名称的JTextField,该名称将在对象创建后可用于垃圾回收:
JTextField myOutput = new JTextField(20);
Now there are 2 solutions : 现在有2个解决方案:
1>Specify the size of JTextField in class definition like : 1>在类定义中指定JTextField的大小,例如:
JTextField myOutput = new JTextField(20); // new object created for JTextField
2> Do not create a new JTextField Object in Constructor like : 2>不要在构造器中创建新的JTextField对象,例如:
myOutput = new JTextField(20);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.