aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Some help on my method of building a sub-dialog Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Some help on my method of building a sub-dialog" Watch "Some help on my method of building a sub-dialog" New topic
Author

Some help on my method of building a sub-dialog

Jon Swanson
Ranch Hand

Joined: Oct 10, 2011
Posts: 193
I have a sub-dialog that I reuse in my program. I have a class to create it and then I make it visible or not as needed. I also thought that I was handling the case where an error occurs trying to make it in the first place. Here is the simplest bit of code for illustration-



In 'real life' the constructor has a try-catch block. I stripped out everything except what I do if it fails. What has me troubled is that rd is not null if the initialization fails. So I get the error message, and then an empty dialog pops up.

Java complains if I change the return statement to 'return null.'

I was liking the fact that any graphical interaction was encapsulated in ReportDialog, so the routine that actually calls it could run without a GUI, if I preferred. I could call a method in ReportDialog that either did the initialization and returned a success/failure status or I could rethrow an exception for the calling routine to catch. I'm not short of ways to keep the dialog from appearing if the initialization fails. But before I choose a method that may end up being a bad habit, I thought I'd ask some advice from people with more experience. How should I structure things so I don't have a dialog pop-up if there is an error when I build it?
Tony Docherty
Bartender

Joined: Aug 07, 2007
Posts: 1946
    
  28
You can't return anything from a constructor.
If you detect an error in a constructor and you don't want the object to be created you throw an exception.
Jon Swanson
Ranch Hand

Joined: Oct 10, 2011
Posts: 193
The class can have methods, however.



I was wondering whether rethrowing the exception was the only approach people use or there are other common ways of handling the situation.
Ranganathan Kaliyur Mannar
Bartender

Joined: Oct 16, 2003
Posts: 1075
    
  10

You can use the Builder pattern. That is quite common these days particularly to build GUI widgets. JavaFX uses a lot of builders.


Ranga.
SCJP 1.4, OCMJEA/SCEA 5.0.
Jon Swanson
Ranch Hand

Joined: Oct 10, 2011
Posts: 193
Thanks, I'll look into that.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Some help on my method of building a sub-dialog
 
Similar Threads
Query
My very own MVC framework...
Null pointer exception
Get rid of line numbers
Fast text searching