Leon Anavi
IT Tips && Tricks

Java

Created: 23.07.2009 22:20 Last Modified: 23.07.2009 22:23 Views: 7697
Keywords: dialog, JDialog, modal, Swing

Swing Dialogs

Introduction to Dialogs

A dialog is an indepentent subwindow of a Swing application. The class defining the dialog must extend class JDialog (part of the javax.swing package). A dialog which requires user interaction before executing anything else is called modal or heavy window.

How to Create a Dialog?

Declare a new class which extends JDialog. At the constructor implement the super constructor with parameters for parent frame (null if none) and status (modal window or not).
Example:
public class MyDialog extends javax.swing.JDialog {
    public MyDialog(java.awt.Frame parent, boolean bModal) {
        super(parent, bModal);
        //TO DO: Add your code for initialization here
    }

How to Use a Dialog?

At appropriate location of you code (for example key, button or menu event) create instance of the dialog, adjust its position and make it visible. As of JDK version 1.5 the method show() is deprecated and must not be used. Instead use the method setVisible() to display the dialog. There are several ways to adjust the position of the dialog:
  • By position – setLocation(Point p) or setLocation(int x, int y)
  • JFrame AppMainFrame = DialogTestApp.getApplication().getMainFrame();
    MyDialog MyDlg = new MyDialog(AppMainFrame, true);
    // Coordinates of the left upper corner of the dialog.
    Point Pos = new Point(20,20);
    MyDlg.setLocation(Pos);
    MyDlg.setVisible(true);
    
  • According to another Swing component - setLocationRelativeTo (Component c)
  • JFrame AppMainFrame = DialogTestApp.getApplication().getMainFrame();
    MyDialog MyDlg = new MyDialog(AppMainFrame, true);
    MyDlg.setLocationRelativeTo(AppMainFrame);
    MyDlg.setVisible(true);
    

Class Reference

JDialog

External Links

How to Make Dialogs

  Home | About | Contact | Disclaimer | Sitemap © 2009-2022 Leon Anavi. All rights reserved.