自定义JOptionPane对话框 [英] Customize JOptionPane Dialog
问题描述
我正在学习java swing。下面的代码是一个catch块,它处理IOException并显示错误消息。
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);
}
我正在考虑在catch块中声明和自定义我自己的JOptionPane比如下面的代码:
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);
但问题是我不知道如何将它作为showMessageDialogue出现在屏幕上方法呢。请帮忙。
提前致谢。
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.
推荐答案
您只需将组件添加到 JPanel
然后添加这个 JPanel
到您的 JOptionPane
,如下面这个小例子所示:
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();
}
});
}
}
这篇关于自定义JOptionPane对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!