Search code examples
javajtextfield

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:

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. Can you explain why this is?


Solution

  • Inside the constructor, you are creating a new variable called myOutput, which is not the same as the instance variable declared above. JTextField myOutput should be myOutput

    EDIT:

    You declare a method-local variable myOutput and add it to your frame. createGUI() uses the instance variable declared at the top of the class, therefore it does not affect the TextField in the frame.