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

后端 未结 2 467
臣服心动
臣服心动 2021-01-19 17:21

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

相关标签:
2条回答
  • 2021-01-19 17:52

    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.

    0 讨论(0)
  • 2021-01-19 18:09

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题