【问题标题】:Is there a way to Change the JOptionPane layout, like the color at the top and the image at the top left?有没有办法改变 JOptionPane 布局,比如顶部的颜色和左上角的图像?
【发布时间】:2012-05-16 09:28:57
【问题描述】:

我很好奇,我想知道是否有办法让 JOptionPane 的顶部变成不同的颜色,比如红色或橙色。我还想知道如何更改 JOptionPane 左侧的图像。我猜这是不可能的,因为它已经是 java 使用的一种方法。但我不是专家。

【问题讨论】:

  • make the top of the JOptionPane into a different color 你的意思是带有关闭按钮的工具栏

标签: java swing joptionpane


【解决方案1】:

这里有三个选项:

  1. 使用相应消息类型的预定义图标之一:
    JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.", "Inane error", JOptionPane.ERROR_MESSAGE);

  2. 使用自定义图标:
    JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.", "Inane custom dialog", JOptionPane.INFORMATION_MESSAGE, icon);

  3. 使用外观和感觉在整个应用程序中使用一致的图标:How to Set the Look and Feel

查看this page of the Java Tutorial 了解有关对话框的更多信息。

【讨论】:

    【解决方案2】:

    您可以将自己的 ImageIcon 添加到 JOptionPane - 查看 API,并尝试使用 Icon 字段调用方法,传入您自己的 ImageIcon 以查看其工作原理。您还可以创建一个复杂的 JPanel,一个完整的包含 GUI 的 JPanel,并将其作为 JOptionPane 的基础,只需将其作为 JOptionPane.showXXX(...) 方法的 Object 参数(通常是第二个参数)传入即可。

    另一种选择是创建和使用您自己的模态 JDialog。

    工作代码:

    import java.awt.Color;
    import javax.swing.*;
    
    public class JOptionPaneExample
    {
        private void createAndDisplayGUI()
        {
            JOptionPane.showMessageDialog(null, getOptionPanel(), "Modified JOptionPane : ", JOptionPane.PLAIN_MESSAGE);
        }
    
        public static void main(String... args)
        {   
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    new JOptionPaneExample().createAndDisplayGUI();
                }
            });
        }
    
        private JPanel getOptionPanel()
        {
            JPanel panel = new JPanel();
            panel.setOpaque(true);
            panel.setBackground(Color.RED);
            try
            {
                java.net.URL url = new java.net.URL("http://gagandeepbali.uk.to/gaganisonline/images/swing/geek.gif");
                ImageIcon image = new ImageIcon(url);
                JLabel label = new JLabel("I am one MODIFIED JOPTIONPANE's LABEL.", image, JLabel.RIGHT);
                panel.add(label);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            return panel;
        }
    }
    

    【讨论】:

    • 我更喜欢@rolve 的回答。 1+ 给他。
    • @HovercraftFullOfEels :很抱歉编辑,不过,我曾经从你那里学到的东西太棒了,所以只添加了一个小代码部分。我希望所有人都可以学习这个东西,看看它是多么的简单和美妙:-) 如果我做错了什么,就把它恢复回来:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    相关资源
    最近更新 更多