Alert Popup in Java

Sheeraz Gul Apr 21, 2022
Alert Popup in Java

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:

Alert Popup

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

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 Facebook

Related Article - Java GUI