jdialog in java
JDialog
is a class in Java Swing that provides a pop-up window that can be used to get user input or to display some information. It is similar to a JFrame
, but it is typically used for more specialized purposes, such as displaying a modal dialog box.
Here's an example of how to create and display a simple JDialog
in Java:
import javax.swing.*; public class MyDialog extends JDialog { public MyDialog(JFrame parent, String title, String message) { super(parent, title, true); // create a modal dialog JPanel panel = new JPanel(); JLabel label = new JLabel(message); panel.add(label); getContentPane().add(panel); setDefaultCloseOperation(DISPOSE_ON_CLOSE); pack(); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); new MyDialog(frame, "My Dialog", "Hello, world!"); } }
In this example, we create a new class MyDialog
that extends JDialog
. In the constructor, we create a simple JPanel
with a JLabel
that displays a message. We add the panel to the dialog's content pane, set the default close operation to DISPOSE_ON_CLOSE
, and pack and center the dialog. Finally, we make the dialog visible.
In the main
method, we create a new JFrame
and make it visible. Then we create a new instance of MyDialog
, passing the frame as the parent, a title, and a message. The dialog is displayed modally, which means that it will block input to the parent frame until it is closed.