Is there a way to Change the JOptionPane layout, like the color at the top and the image at the top left?

强颜欢笑 提交于 2019-12-31 00:00:03

问题


I am curious, I am wondering if there exist a way to make the top of the JOptionPane into a different color, say red or orange. Also i was wondering how to change the image on the left of the JOptionPane. I am guessing it is not possible because it is already a method being used from java. But i am no expert.


回答1:


There are three options here:

  1. Use one of the predefined icons using the respective message type:
    JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.", "Inane error", JOptionPane.ERROR_MESSAGE);

  2. Use a custom icon:
    JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.", "Inane custom dialog", JOptionPane.INFORMATION_MESSAGE, icon);

  3. Use a look & feel to have consistent icons all over your application: How to Set the Look and Feel

Have a look at this page of the Java Tutorial for more information on dialogs.




回答2:


You can add your own ImageIcon to a JOptionPane -- check out the API, and try calling the methods with an Icon field, passing in your own ImageIcon to see how this works. You can also create a complex JPanel, a full fledged GUI-containing JPanel, and make it the basis for your JOptionPane, simply by passing it in as the Object parameter (usually the second paramter) of the JOptionPane.showXXX(...) method.

Another option is to create and use your own modal JDialog.

A working code :

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


来源:https://stackoverflow.com/questions/10489437/is-there-a-way-to-change-the-joptionpane-layout-like-the-color-at-the-top-and-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!