How to create a Popup window using Java swing

In this post, we will make a Popup window in Java Swing.

Code: Popup window using Java Swing

import javax.swing.*;
import java.awt.*;

public class PopupWindow {
    public static void main(String[] args) {
        JFrame frm = new JFrame("Popup Window");
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JButton btn = new JButton(" Click Me! ");
        btn.addActionListener(e -> {
            JOptionPane.showMessageDialog(frm, " Thank you for learning from CodeSpeedy ");
        });
        
        frm.setLayout(new FlowLayout());
        frm.getContentPane().add(btn);
        frm.setSize(350,200);
        frm.setVisible(true);
        frm.setLocationRelativeTo(null);
    }
}

Output

Here is the output of the above code:

Create popup window in Java Swing

Explanation

  1. First, we import the required classes from the javax.swing and java.awt packages.
  2. Next, we create a class called PopupWindow and then we declared the main method inside it. Inside the main method, we create a JFrame object named frm and give the title as Popup Window.
    We make use of the method setDefaultCloseOperation()to exit the program when the frame is closed.
  3. Next, we create a JButton object name it btn and then label it Click Me!. Next, we also add ActionListener to the button.
  4. We use the JOptionPane class to display the message ” Thank you for learning from CodeSpeedy ” when the button is clicked.
  5. Then we use the getContentPane().add() method to add a button to the content pane of the frame.
  6. Next, we make use of the method setSize() to adjust the frame size to 350×200 pixels.
  7. In the end, we make the frame appear by using the method  setVisible(true) and also set the position of the frame to the center of the screen by making use of the method setLocationRelativeTo(null).

Thank you for learning from CodeSpeedy. Make sure to clear any doubts you have in the comments section of this post.

You can also read:

Leave a Reply

Your email address will not be published. Required fields are marked *