9

我正在学习java swing。下面的代码是一个处理 IOException 并显示错误消息的 catch 块。

 catch(IOException e)
    {
        System.out.println("IOException");
        JOptionPane.showMessageDialog(null,"File not found",null,
                                    JOptionPane.ERROR_MESSAGE);
    }

我正在考虑在 catch 块中声明和自定义我自己的 JOptionPane,如下面的代码:

JOptionPane jop=new JOptionPane();
        jop.setLayout(new BorderLayout());
        JLabel im=new JLabel("Java Technology Dive Log",
                new ImageIcon("images/gwhite.gif"),JLabel.CENTER);
        jop.add(im,BorderLayout.NORTH);
        jop.setVisible(true);

但问题是我不知道如何让它像 showMessageDialogue 方法那样出现在屏幕上。请帮忙。提前致谢。

4

3 回答 3

24

您可以简单地将组件添加到 a 中JPanel,然后将其添加JPanel到您的JOptionPane中,如以下小示例所示:

import java.awt.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
import javax.imageio.ImageIO;

public class JOptionPaneExample {

    private void displayGUI() {
        JOptionPane.showConfirmDialog(null,
                        getPanel(),
                        "JOptionPane Example : ",
                        JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.PLAIN_MESSAGE);
    }

    private JPanel getPanel() {
        JPanel panel = new JPanel();
        JLabel label = new JLabel("Java Technology Dive Log");
        ImageIcon image = null;
        try {
            image = new ImageIcon(ImageIO.read(
                    new URL("http://i.imgur.com/6mbHZRU.png")));
        } catch(MalformedURLException mue) {
            mue.printStackTrace();
        } catch(IOException ioe) {
            ioe.printStackTrace();
        } 

        label.setIcon(image);
        panel.add(label);

        return panel;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JOptionPaneExample().displayGUI();
            }
        });
    }
}
于 2012-09-02T10:42:12.357 回答
6

我想这取决于有什么问题JOptionPaneshowMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon)

JOptionPane.showMessageDialog(null, "Java Technolgy Dive Log", "Dive", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("images/gwhite.gif"));

对话

于 2012-09-02T09:42:49.567 回答
3
JOptionPane jop = new JOptionPane();
JDialog dialog = jop.createDialog("File not found");
dialog.setLayout(new BorderLayout());
JLabel im = new JLabel("Java Technology Dive Log", new ImageIcon("images/gwhite.gif"), JLabel.CENTER);
dialog.add(im, BorderLayout.NORTH);
dialog.setVisible(true);
于 2012-09-02T09:46:59.503 回答