自定义JOptionPane对话框

时间:2012-09-02 09:33:16

标签: java swing jlabel joptionpane imageicon

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

 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方法一样出现在屏幕上。请帮忙。 提前致谢。

3 个答案:

答案 0 :(得分:19)

您只需将组件添加到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();
            }
        });
    }
}

答案 1 :(得分: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"));

Dialog

答案 2 :(得分: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);