What are the differences between JFrame and JDialog in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

JFrame

  • The components added to the frame are referred to as its contents, these are managed by the contentPane. To add a component to a JFrame, we must use its contentPane instead.
  • A JFrame contains a window with title, border, (optional) menu bar and user-specified components.
  • A JFrame can be moved, resized, iconified and it is not a subclass of JComponent.
  • By default, JFrame is displayed in the upper-left corner of the screen. To display a frame at a specified location, we can use the setLocation(x, y) method in the JFrame class.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameDemo {
   public static void main(String s[]) {
      JFrame frame = new JFrame("JFrame Demo");
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
      JLabel lbl = new JLabel("JFrame Demo");
      lbl.setPreferredSize(new Dimension(175, 100));
      frame.getContentPane().add(lbl, BorderLayout.CENTER);
      frame.setSize(375, 275);
      frame.setVisible(true);
   }
}

Output

JDialog

  • The JDialog is very similar to a JFrame except that the JDialog can be set modally. Modal means that no other window can be used or activated while the corresponding JDialog is being displayed.
  • Modal dialogs block input to other top-level windows and Modeless dialogs allow input to other windows.
  • Unlike JFrame, JDialog does not hold minimize and maximize buttons at the top right corner of the window.

Example

import javax.swing.JDialog;
import javax.swing.JLabel;
public class JDialogDemo extends JDialog {
   public static void main(String[] args) {
      try {
         JDialogDemo dialog = new JDialogDemo();
         dialog.setVisible(true);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }  
   public JDialogDemo() {
      setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
      setTitle("Welcome to Tutorials Point");
      setBounds(100, 100, 359, 174);
      getContentPane().setLayout(null);
      JLabel label = new JLabel("Welcome to Tutorials Point");
      label.setBounds(86, 37, 175, 29);
      getContentPane().add(label);
   }
}

Output

raja
Published on 03-Jul-2019 23:16:37
Advertisements