0

first of all, i don't speak correct english, and sorry for that!

I am making a stock system in Java, and it's working, but i have a doubt about the correct use of dispose() from JDialog instance.

My code:

public Usuario getUsuario() {
    this.setVisible(true);
    this.dispose();
    return new VentanaConfigurarPrivilegios(new Usuario(textField.getText(), new String(passwordField.getPassword()))).getUsuario();
}

this function works and returns a new Usuario from the new Instance of VentanaConfigurarPrivilegios calling to getUsuario(), but the doubt is about the last 2 lines, i'm disposing the JDialog, and after, is passing a text from textFields, it work fine, but i'm not sure that i am doing this in a correct way, and i would not like that the code fails when is using.

Again, sorry for my english!! Thanks.

Nirav Gadhiya
  • 6,342
  • 2
  • 37
  • 76
  • Is the dialog declared modal? I guess it must be if the code is working as you expect. For better help (better than guesses) sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Oct 28 '13 at 15:26
  • You don't need to call dispose() at all normally. And *if* you call dispose(), all it does is release the native window handle, saving some memory. – Durandal Oct 28 '13 at 16:22

1 Answers1

0

I think the question is that once you dispose() a dialog it is eligible for garbage collection, so would garbage collection ever happen before you are able to access the text from the text fields displayed on the dialog.

I don't think it would be a problem but just in case you can reorder your code:

this.setVisible(true);
VentanaConfigurarPrivilegios data = new Vent...(...);
this.dispose();
return data;
camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    That's not how GC works. As long as there's a reference to the object, the object is not GC'd. – Darkhogg Oct 28 '13 at 15:39
  • 1
    I agree with @Darkhogg. All `dispose()` does is to release *native* resources. That's it. The JDialog object itself and all of its components are still available to be queried as long as there exists valid references to it. – Hovercraft Full Of Eels Oct 28 '13 at 15:40
  • Thanks for repply, a last question, que variable "data" when i call "dispose()", also be deleted? – user2928577 Oct 28 '13 at 15:42
  • @user2928577 I think that quite common issue with out of memory e.i. [if I remember correctly rest is here](http://stackoverflow.com/a/19598199/714968), read comments and follows link in my comment too – mKorbel Oct 28 '13 at 17:32
  • 3
    Thanks guys, I was over thinking things. – camickr Oct 28 '13 at 18:41