在JOptionPane中添加图片

4

我想知道如何在消息对话框中添加图片。我尝试了下面的代码,但是图片无法显示。

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

什么是消息对话框? - Hovercraft Full Of Eels
从showMessageDialog方法开始 - user1911773
非常感谢大家的帮助!我按照Mel和MadProgrammer的建议解决了问题! - user1911773
3个回答

20

JOptionPane 是一个非常灵活的 API。

你应该首先查看 Java API 文档Java Trails,特别是如何使用对话框

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

            }
        });
    }
}

3
不错的地球仪。这是我见过的最好的“Hello world”图形用户界面版本。 :) - Andrew Thompson

5

从JOptionPane的javadoc文档中可以得知:

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

只需将您的图像制作为一个Icon,并将其作为第5个参数添加即可。

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

不要忘记在使用之前定义image2(将该行向上移动)。

5

什么是MessageDialogBox?如果您想要在JOptionPane中添加图像,可以使用接受Icon的方法重载来解决此问题。另一种方法是创建一个包含图像和其他组件的JPanel或JLabel,然后在JOptionPane中显示它。


我在代码中使用了JLabel,但是我该如何将它放入JOptionPane中呢?注意:我是Java和编程的新手。 - user1911773
+1,还有HTML格式化显示多个图像并在运行时调整它们的大小。 - Andrew Thompson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接