自定义JOptionPane对话框

Vic*_*jee 6 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);
    }
Run Code Online (Sandbox Code Playgroud)

我想在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);
Run Code Online (Sandbox Code Playgroud)

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

nIc*_*cOw 22

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


Mad*_*mer 5

我想这取决于什么是错的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"));
Run Code Online (Sandbox Code Playgroud)

对话

  • 你必须惊讶于盲目投票.您是否愿意告诉我为什么您觉得需要投票,所以我们都可以了解为什么这个问题不适合您? (2认同)