【问题标题】:Add Image to JOptionPane将图像添加到 JOptionPane
【发布时间】:2012-12-07 10:55:07
【问题描述】:

我想知道如何将图像添加到消息对话框。试了下面的代码,找不到图片了

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

【问题讨论】:

  • 什么是 MessageDialogBox?
  • 来自 showMessageDialog 方法
  • 感谢大家的帮助!我是根据 Mel 和 MadProgrammer 的建议想出来的!

标签: java image swing joptionpane messagedialog


【解决方案1】:

JOptionPane 是一个非常灵活的 API。

您的第一个停靠港应该是Java API DocsJava Trails,具体是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);

            }
        });
    }
}

【讨论】:

  • 漂亮的地球仪。这是我见过的“Hello world”最好的 GUI 版本。 :)
【解决方案2】:

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

【讨论】:

  • 我使用了 JLabel,正如您在代码中看到的那样,但我如何将它放在 JOptionPane 中。注意:我是 Java 和一般编程新手
  • +1,还有 HTML 格式用于显示多个图像并在运行时调整它们的大小。
【解决方案3】:

来自 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 (向上移动)

【讨论】:

    猜你喜欢
    • 2016-01-19
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 2021-12-01
    • 2011-06-27
    • 2013-08-04
    相关资源
    最近更新 更多