Alert Popup in Java
Sheeraz Gul
Apr 21, 2022

The Swing
library shows the alert popups in Java. This tutorial demonstrates how to create an alert message in Java.
Alert Popup in Java
As mentioned above, the Swing
library creates alert popups in Java. We use JOptionPane
API to create a dialogue box and JOptionPane.showMessageDialog()
API to show the alert message.
Let’s try an example that will show an alert popup on click. See example:
package delftstack;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.LayoutManager;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Alert_Popup {
public static void main(String[] args) {
Create_Main();
}
private static void Create_Main() {
JFrame Alert_Frame = new JFrame("Alert Window");
Alert_Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Create_Popup(Alert_Frame);
Alert_Frame.setSize(400, 200);
Alert_Frame.setLocationRelativeTo(null);
Alert_Frame.setVisible(true);
}
private static void Create_Popup(final JFrame Alert_Frame){
JPanel Alert_Panel = new JPanel();
LayoutManager Alert_Layout = new FlowLayout();
Alert_Panel.setLayout(Alert_Layout);
JButton Alert_Button = new JButton("Click Here to Show Alert!");
Alert_Button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Alert_Frame, "Hello This is Alert from Delfstack!");
}
});
Alert_Panel.add(Alert_Button);
Alert_Frame.getContentPane().add(Alert_Panel, BorderLayout.CENTER);
}
}
The code above will show the alert popup on click. See output:
Author: Sheeraz Gul
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn FacebookRelated Article - Java GUI
- Background Colors in Java
- Button Group in Java
- Best GUI Builders for Java Swing Applications
- Create Java Progress Bar Using JProgressBar Class
- Tic Tac Toe GUI in Java