Java Program to set an icon for JOptionPane

Java 8Object Oriented ProgrammingProgramming

Let us first set an image with Image Icon class −

ImageIcon icon = new ImageIcon(new URL("http://www.tutorialspoint.com/images/css.png"));

Now, set it to a component −

JLabel label = new JLabel(icon);

Add the component to the panel −

JPanel panel = new JPanel(new GridBagLayout());
panel.add(label);

The following is an example to set an icon for JOptionPane −

Example

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


raja
Published on 04-Jun-2019 07:12:33
Advertisements