Add Image to JOptionPane

不羁岁月 提交于 2019-11-29 15:13:03

JOptionPane is a very flexible API.

Your first port of call should be the Java API Docs and the Java Trails, specific How to use Dialogs

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);

            }
        });
    }
}

From the javadoc on JOptionPane:

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

Just make an Icon of your image and add it as a 5th parameter.

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

Don't forget to define image2 before you use it (move the line up)

What is a MessageDialogBox? If you mean add an image to a JOptionPane, there are method overloads that accept an Icon, and so this is one way to solve this. Another is to create a JPanel or JLabel with your image and other components and then display this in the JOptionPane.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!