Add image to JOptionPane

I am wondering how to add an image to the MessageDialog Box. I tried the code below and the image was not found anywhere

else if(button == B){ String text = "blahblahblahblahblah"; JTextArea textArea = new JTextArea(text); textArea.setColumns(30); textArea.setLineWrap( true ); textArea.setWrapStyleWord( true ); textArea.setSize(textArea.getPreferredSize().width, 1); Font font = new Font("Verdana", Font.BOLD, 12); textArea.setFont(font); textArea.setForeground(Color.BLUE); JOptionPane.showMessageDialog( null, textArea, "Border States", JOptionPane.PLAIN_MESSAGE); image2 = new ImageIcon(getClass().getResource("borderstates.jpg")); label2 = new JLabel(image2); add(label2); 
+4
source share
3 answers

JOptionPane is a very flexible API.

Your first port of call should be Java API Docs and Java Trails specific How to use dialog boxes

enter image description hereenter image description here

 public class TestOptionPane04 { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } ImageIcon icon = new ImageIcon(TestOptionPane04.class.getResource("/earth.png")); JOptionPane.showMessageDialog( null, "Hello world", "Hello", JOptionPane.INFORMATION_MESSAGE, icon); JOptionPane.showMessageDialog( null, new JLabel("Hello world", icon, JLabel.LEFT), "Hello", JOptionPane.INFORMATION_MESSAGE); } }); } } 
+17
source

From javadoc on JOptionPane:

 public static void showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon) throws HeadlessException 

Just create an Icon your image and add it as the 5th parameter.

 JOptionPane.showMessageDialog(null, textArea, "Border States", JOptionPane.PLAIN_MESSAGE, image2); 

Remember to define image2 before using it (move the line up)

+5
source

What is MessageDialogBox? If you want to add an image to JOptionPane, there are overloads of methods that accept the icon, and therefore this is one way to solve this problem. Another is to create a JPanel or JLabel with your image and other components, and then display that in JOptionPane.

+4
source

All Articles