JDialog in Java With Examples

JDialog in Java

Another class from the window category is javax.swing.JDialog. The JDialog is very similar to a JFrame except that the JDialog can be made modal. Modal means that while the relevant JDialog is displayed, no other window can be used or activated. For this reason, the JDialog is often used as a basis for error messages or queries to the user (i.e “Do you really want to delete the file?”), to which the user must react before he can continue with the program. The JDialog cannot manage JInternalFrame ‘s.


Now let’s look at an example of how to create and display a dialog:

We create a JDialog object using the new operator. Unlike the JFrame class, the JDialog constructor can not be given a title. Therefore, you have to set the title using the setTitle method. Then we use the setSize method to set the width to 300 and the height to 200 pixels. We also make our dialog modal, but in this simple example, this has no noticeable impact since the dialog is the only one in our application anyway. Finally, we use the setVisible method to display the dialog.


After running the source code above, you should get the following screen:

JDialog

We have now created a simple window, but we don’t yet know how to fill this with elements.



Now, with the help of a simple JLabel element, we will label this window with a fixed text. A label is nothing more than lettering. With this simple example, we just want to demonstrate how you can add elements without much effort and without a special layout. 

The add method adds new components to our frame. We now extend the above example:

As you can see, here we just included an import statement for our JLabel and called the add method. We passed an object of the JLabel class as a parameter to the add method. When the JLabel object was created, the text to be displayed was passed to the constructor. 


When executing the modified source code, we now get the following picture:

JDialog

As you can see, the text we specified for the JLabel is now in our frame. Using the add method, any control elements can be added to our interface. We will show how these work in detail in the next articles.

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: