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

3 回答 3

20

JOptionPane是一个非常灵活的 API。

您的第一个调用端口应该是Java API DocsJava Trails,具体如何使用对话框

在此处输入图像描述在此处输入图像描述

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

            }
        });
    }
}
于 2012-12-20T00:47:06.860 回答
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(向上移动)

于 2012-12-20T00:27:51.690 回答
5

什么是消息对话框?如果您的意思是向 JOptionPane 添加图像,则存在接受图标的方法重载,因此这是解决此问题的一种方法。另一种方法是使用您的图像和其他组件创建 JPanel 或 JLabel,然后将其显示在 JOptionPane 中。

于 2012-12-20T00:19:24.887 回答