Java

Java Swing JOptionPane Html Content Example

In the previous tutorial, we learn about the basic Swing JOptionPane and saw different types of dialogue boxes. Here  we are going to see how to add html content including images to JOptionPane.

JOptionPane Html Content :

MyOptionPane.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

class MyJOptionPane extends JFrame {
    JButton Warning, Message;
    JPanel ButtonPanel;
    URL url;

    MyJOptionPane() {
        super("JOptionPane Demo");

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Warning = new JButton("Warning for U");
        Warning.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                String Msg = "Brain Draining  has become a serious
";                 Msg = Msg                         + " problem which needs immediate attention
";                 Msg = Msg + " What do u think ";                 JOptionPane.showMessageDialog(ButtonPanel, Msg, "HTML Message",                         JOptionPane.WARNING_MESSAGE);             }         });         Message = new JButton("Click me..");         Message.addActionListener(new ActionListener() {             public void actionPerformed(ActionEvent ae) {                 try {                     url = new URL(                             "file:\\C:\\Desktop\\images\\fox.png");                 } catch (Exception e) {                     System.out.println("File not Loaded" + e);                 }                 String ImageSrc = "";                 JOptionPane.showMessageDialog(ButtonPanel, "" + ImageSrc                         + "
How is the Message
",                         "HTML Message with Image",                         JOptionPane.INFORMATION_MESSAGE);             }         });         ButtonPanel = new JPanel();         ButtonPanel.add(Warning);         ButtonPanel.add(Message);         getContentPane().add(ButtonPanel);         setSize(300, 300);         setVisible(true);     } } class JOptionPane_HTML {     public static void main(String args[]) {         MyJOptionPane frame = new MyJOptionPane();     } }

Output :

JOptionPane Html

JOptionPane HTML Content :

JOptionPane Html 1

JOptionPane with Images:

JOptionPane Html Image

Happy Learning :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment