开发者

JTextField variable returns null outside of actionlistener?

开发者 https://www.devze.com 2023-03-30 03:53 出处:网络
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.

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);
      开发者_JS百科      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.


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号