Simple Custom JDialog Examples.

Written by Sean R. Owens (sean at guild dot net). Share and enjoy. http://darksleep.com/player

This is a simple example of how to use JDialog in Java.

This example assumes basic familiarity with Java, especially with how to compile and run programs. If you need help compiling and running these, don't ask me. Go somewhere else. (I suggest IRC channel #java on irc.freenode.org - they just love simple questions like those.)

A Very Simple Example

TestTheDialog.java (source, 53 lines)

CustomDialog.java (source, 54 lines)

This is a very simple example of using a custom JDialog. It consists of two files. The first one, TestTheDialog, simply creates a JFrame, and adds a button to the JFrame. When the button is clicked on, TestTheDialog creates an instance of CustomDialog, passing a String as a parameter, "Do you like Java?". It may not be obvious, but at this point, because CustomDialog is a 'modal' dialog, it takes over, gobbling all further user mouse clicks or key strokes. TestTheDialog freezes, waiting for CustomDialog to finish running. CustomDialog is the second file. It simply takes the string passed, uses it to create a JLabel, and then adds that label as well as two buttons labeled "Yes" and "No" to itself. Then it waits for the user to do something. CustomDialog has a private boolean member, 'answer', that is initially set to 'false'. If the user clicks 'yes', answer is set to true. If the user clicks 'no', answer is set to false. In either case, after the user clicks the button, CustomDialog removes itself from the screen with setVisible(false). This also returns control to TestTheDialog. At this point, TestTheDialog unfreezes, and gets the stored answer from CustomDialog by using the method, 'getAnswer()'.


Last modified: Wed May 27 19:16:10 EDT 2009