How to make a JFrame Modal in Swing java

How to make a JFrame Modal in Swing java

In Swing, you can create a modal JFrame by using a JDialog with a parent JFrame. A modal dialog blocks user interaction with other parts of the application until it is closed. Here's how you can create a modal JDialog:

import javax.swing.*; public class ModalJFrameExample { public static void main(String[] args) { JFrame parentFrame = new JFrame("Parent Frame"); parentFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); parentFrame.setSize(300, 200); JButton openModalButton = new JButton("Open Modal Dialog"); openModalButton.addActionListener(e -> { // Create and show the modal dialog JDialog modalDialog = new JDialog(parentFrame, "Modal Dialog", true); modalDialog.setSize(200, 100); modalDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); modalDialog.setLocationRelativeTo(parentFrame); JLabel label = new JLabel("This is a modal dialog."); modalDialog.add(label); modalDialog.setVisible(true); }); parentFrame.add(openModalButton); parentFrame.setVisible(true); } } 

In this example:

  1. We create a JFrame called parentFrame and add a button called openModalButton to it.

  2. When the button is clicked, we create a JDialog called modalDialog with the parent frame as the first argument. The true argument in the constructor makes it a modal dialog.

  3. We set the size, close operation, and location of the modal dialog.

  4. We add a JLabel to the modal dialog to display a message.

  5. Finally, we make the modal dialog visible using modalDialog.setVisible(true). The parent frame remains blocked until the modal dialog is closed.

This way, you can create a modal JDialog in Swing to block user interaction with the parent frame until the modal dialog is closed.


More Tags

emoticons mktime big-o amazon-s3 text-widget nco azure-cosmosdb-sqlapi sqldatareader jstree imbalanced-data

More Java Questions

More Animal pregnancy Calculators

More Biochemistry Calculators

More Fitness Calculators

More Chemistry Calculators