Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

java - Customize JOptionPane Dialog

I am learning java swing. The code below is a catch block which handles an IOException and shows a error message.

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

I was thinking of declaring and customizing a JOptionPane of my own inside the catch block like the code below:

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

But the problem is that I don't know how to make it appear on the screen as the showMessageDialogue method does. Please help. Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can simply add your components to a JPanel and then add this JPanel to your JOptionPane, as shown in this small example :

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...