Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 964
Renuz Avatar asked Dec 13 '22 02:12

Renuz


2 Answers

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.

like image 58
rolve Avatar answered Jan 05 '23 00:01

rolve


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;
    }
}
like image 20
Hovercraft Full Of Eels Avatar answered Jan 04 '23 22:01

Hovercraft Full Of Eels