Is there a way to change the layout of JOptionPane, for example, the color at the top and the image in the upper left?

I'm curious, I'm wondering if there is a way to make the top of the JOptionPane a different color, like red or orange. I was also interested in how to change the image to the left of JOptionPane. I assume this is not possible because it is already a method used from java. But I am not an expert.

+4
source share
2 answers

There are three options here:

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

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

  • Use the look to have consistent icons throughout your application: How to customize the look and feel

Check out this Java tutorial page for more information on dialogs.

+7
source

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

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

Work 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 LABEL.", image, JLabel.RIGHT); panel.add(label); } catch(Exception e) { e.printStackTrace(); } return panel; } } 
+6
source

All Articles