use*_*773 4 java swing image joptionpane messagedialog
我想知道如何将图像添加到MessageDialog框.我尝试了下面的代码,图像无处可寻
else if(button == B){
String text = "blahblahblahblahblah";
JTextArea textArea = new JTextArea(text);
textArea.setColumns(30);
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
textArea.setSize(textArea.getPreferredSize().width, 1);
Font font = new Font("Verdana", Font.BOLD, 12);
textArea.setFont(font);
textArea.setForeground(Color.BLUE);
JOptionPane.showMessageDialog(
null, textArea, "Border States", JOptionPane.PLAIN_MESSAGE);
image2 = new ImageIcon(getClass().getResource("borderstates.jpg"));
label2 = new JLabel(image2);
add(label2);
Run Code Online (Sandbox Code Playgroud)
Mad*_*mer 19
JOptionPane 是一个非常灵活的API.
您的第一个调用端口应该是Java API Docs和Java Trails,具体如何使用Dialogs


public class TestOptionPane04 {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
ImageIcon icon = new ImageIcon(TestOptionPane04.class.getResource("/earth.png"));
JOptionPane.showMessageDialog(
null,
"Hello world",
"Hello", JOptionPane.INFORMATION_MESSAGE,
icon);
JOptionPane.showMessageDialog(
null,
new JLabel("Hello world", icon, JLabel.LEFT),
"Hello", JOptionPane.INFORMATION_MESSAGE);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
什么是消息对话框?如果您的意思是将图像添加到 JOptionPane,则有接受图标的方法重载,因此这是解决此问题的一种方法。另一种方法是使用您的图像和其他组件创建 JPanel 或 JLabel,然后将其显示在 JOptionPane 中。
从JOptionPane上的javadoc:
public static void showMessageDialog(Component parentComponent,
Object message,
String title,
int messageType,
Icon icon)
throws HeadlessException
Run Code Online (Sandbox Code Playgroud)
只需制作Icon您的图像并将其添加为第5个参数.
JOptionPane.showMessageDialog(null, textArea, "Border States",
JOptionPane.PLAIN_MESSAGE, image2);
Run Code Online (Sandbox Code Playgroud)
在使用之前不要忘记定义image2(向上移动)