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:
Explanation
- First, we import the required classes from the
javax.swing
andjava.awt
packages. - 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 methodsetDefaultCloseOperation()
to exit the program when the frame is closed. - Next, we create a JButton object name it btn and then label it Click Me!. Next, we also add
ActionListener
to the button. - We use the
JOptionPane
class to display the message ” Thank you for learning from CodeSpeedy ” when the button is clicked. - Then we use the
getContentPane().add()
method to add a button to the content pane of the frame. - Next, we make use of the method
setSize()
to adjust the frame size to 350×200 pixels. - 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 methodsetLocationRelativeTo(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