javaswingjdialogswingbuilder

Create a Jdialog that has an icon just like joptionpane


I have a extended JDialog for a custom dialog because it's a bit complicated and I can't create it with JOptionPane but my issue is I still want to add to the JDialog the same icons that JOptionPane has to keep my dialogs similar in the entire app. These are the Icons provided by java in JOptionPane, but when I create a JDialog it doesn't have an Icon, how can I add one just like JOptionPane without changing into a JOptionPane.

enter image description here enter image description here


Solution

  • On MacOS, JOptionPane, left to right, top to bottom, Error; Information; Warning; Question

    enter image description here

    Loaded from UIManager

    enter image description here

    import java.awt.EventQueue;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.UIManager;
    
    public class Main {
        public static void main(String[] args) {
            new Main();
        }
    
        public Main() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame();
                    frame.setLayout(new GridLayout(2, 2));
                    frame.add(new JLabel(UIManager.getLookAndFeel().getDefaults().getIcon("OptionPane.errorIcon")));
                    frame.add(new JLabel(UIManager.getLookAndFeel().getDefaults().getIcon("OptionPane.informationIcon")));
                    frame.add(new JLabel(UIManager.getLookAndFeel().getDefaults().getIcon("OptionPane.warningIcon")));
                    frame.add(new JLabel(UIManager.getLookAndFeel().getDefaults().getIcon("OptionPane.questionIcon")));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
    
                    JOptionPane.showMessageDialog(frame, "Test", "Test", JOptionPane.ERROR_MESSAGE);
                    JOptionPane.showMessageDialog(frame, "Test", "Test", JOptionPane.INFORMATION_MESSAGE);
                    JOptionPane.showMessageDialog(frame, "Test", "Test", JOptionPane.WARNING_MESSAGE);
                    JOptionPane.showMessageDialog(frame, "Test", "Test", JOptionPane.QUESTION_MESSAGE);
                }
            });
        }
    }