如何在Swing中显示带有自定义图标的消息对话框

说明

以下示例展示了如何在Swing中显示带有自定义图标的消息对话框。

我们正在使用以下 API。

  • JOptionPane : 创建一个标准对话框。

  • JOptionPane.showMessageDialog() : 显示消息警报。

  • JOptionPane.PLAIN_MESSAGE : 将警报消息标记为没有图标的普通消息。

代码示例

package com.yiidian;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("一点教程网:Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();
      panel.setLayout(layout);       
      JButton button = new JButton("Click Me!");
      button.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            ImageIcon arrowIcon = null;
            java.net.URL imgURL = SwingTester.class.getResource("arrow.png");
            if (imgURL != null) {
               arrowIcon = new ImageIcon(imgURL);
            }

            JOptionPane.showMessageDialog(frame, "Please ensure compliance!",
               "Swing Tester", JOptionPane.PLAIN_MESSAGE,arrowIcon);
         }
      });

      panel.add(button);
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }  
}

执行效果如下:

热门文章

优秀文章