Jeff
Jeff

Reputation: 95

JTextField variable returns null outside of actionlistener?

I'm making a program that adds and formats files. I actually have many classes, but for the purpose of this question let's say I have two, guidialog and guimain.

In guidialog I have a JTextField and an actionlistener for it. Here is the actionlistner:

public void actionPerformed(ActionEvent event) {
            blockName=textFieldBlockName.getText();
            System.out.println("Made new block: "+blockName);
            canClose=true;

            guimain blockAddWrite = new guimain();
            blockAddWrite.addNewBlockFile();
        }
    });

public String blockName;

Now in guimain I have a formatter which writes a file based on the name given in the text field:

   public void addNewBlockFile() {
      blockdialog blockName = new blockdialog();

      try {
         newBlock = new Formatter("Block" + blockName.blockName + ".java");
         System.out.println("Created File: Block" + blockName.blockName);
      } catch (Exception e) {
         System.out.println("ERROR: Could Not Output Block File");
      }
   }

I do edit and close the file, but it wasn't necessary. But when I try this, all of the stuff in guimain that refers to blockName outputs as "null". I can't figure it out.

Upvotes: 2

Views: 301

Answers (1)

JB Nizet
JB Nizet

Reputation: 691655

That's because in guimain, you're not using the blockName field of the dialog where the user entered something: you're using the blockName field of another, newly constructed dialog:

public void addNewBlockFile() {
    blockdialog blockName = new blockdialog();
    ^--- the dialog is not the one where the user entered something. It's a new one.

You should pass the blockName from the dialog to the guimain:

public void actionPerformed(ActionEvent event) {
        blockName=textFieldBlockName.getText();
        System.out.println("Made new block: "+blockName);
        canClose=true;

        guimain blockAddWrite = new guimain(blockName); // we construct a guimain instance with the entered text
        blockAddWrite.addNewBlockFile();
    }
});

Side notes:

  • you should not use public fields. Use getter methods.
  • classes should be start with an upper-case and be spelt in CamelCase: GuiMain.

Upvotes: 2

Related Questions