Set an Icon for JOptionPane in Java



In this program, we will learn how to set a custom icon in a JOptionPane using Java's Swing framework. A JOptionPane allows displaying dialog boxes for different purposes such as messages, inputs, or confirmations. In this example, we will create a dialog box with a custom image icon displayed alongside some text. This can be particularly useful for creating visually appealing user interfaces.

Problem Statement

Write a Java program to set an icon for JOptionPane. Below is the demonstration of the same ?

Output


Steps to set an icon for JOptionPane

Following are the steps to set an icon for JOptionPane ?

  • Import the necessary classes from java.awt, java.net and javax.swing package.
  • First, we create an ImageIcon object using an image URL, which will serve as the icon in the dialog.
  • Next, we create a JLabel to hold the icon and add it to a panel using GridBagLayout.
  • Another panel is created using GridLayout to add multiple text labels.
  • These panels are combined in a third panel using BorderLayout to arrange the text and icon.
  • Finally, the combined panel is displayed in a JOptionPane dialog using showMessageDialog()

Java program to set an icon for JOptionPane

The following is an example of setting an icon for JOptionPane ?

package my;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingDemo {
    public static void main(String[] args) throws Exception {
        ImageIcon icon = new ImageIcon(new URL("http://www.tutorialspoint.com/images/css.png"));
        JLabel label = new JLabel(icon);
        JPanel panel = new JPanel(new GridBagLayout());
        panel.add(label);
        JPanel textPanel = new JPanel(new GridLayout(5, 3));
        for (int i = 0; i < 10; i++) {
            textPanel.add(new JLabel("Learn CSS"));
        }
        JPanel panel2 = new JPanel(new BorderLayout());
        panel2.add(textPanel);
        panel2.add(panel, BorderLayout.EAST);
        JOptionPane.showMessageDialog(null, panel2, "Course",JOptionPane.DEFAULT_OPTION);
    }
}

Output

Code Explanation

In this program, we first load an image from a URL and use it to create an ImageIcon object. This icon is placed inside a JLabel component, which is then added to a panel using GridBagLayout for positioning. We also create a text panel with multiple labels arranged in a grid using GridLayout. Both panels are combined into a BorderLayout panel, where the icon is positioned to the right of the text. This final panel is then displayed in a JOptionPane using the showMessageDialog() method, which pops up a dialog box with the icon and text.

Updated on: 2024-09-20T21:38:14+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements