![](/img/trans.png)
[英]Why can't I call an inherited public method without prefacing it with a reference from main method?
[英]Why can I not call a public method of a created object?
當我嘗試運行此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());
}
}
似乎它沒有注冊createGUI()方法。 你能解釋為什么嗎?
在構造函數內部,您正在創建一個名為myOutput
的新變量,該變量與上面聲明的實例變量不同。 JTextField myOutput
應該是myOutput
編輯:
您聲明一個方法局部變量myOutput
並將其添加到框架中。 createGUI()
使用在類頂部聲明的實例變量,因此它不會影響框架中的TextField
。
我只是在擴展blueygh2提供的答案。 主要的問題是:
您沒有在類中給定JTextField的大小,默認情況下將為0
private JTextField myOutput = new JTextField();//no size specified
同樣在構造函數中,您正在聲明另一個具有相同名稱的JTextField,該名稱將在對象創建后可用於垃圾回收:
JTextField myOutput = new JTextField(20);
現在有2個解決方案:
1>在類定義中指定JTextField的大小,例如:
JTextField myOutput = new JTextField(20); // new object created for JTextField
2>不要在構造器中創建新的JTextField對象,例如:
myOutput = new JTextField(20);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.