Search code examples
javaswingjoptionpanejdialog

How to convert a JOptionPane to a JDialog


I need to convert a JOptionPage to a JDialog, because I need to get rid of that quirky "OK" button. Below is the code...

JOptionPane.showMessageDialog(null, Interface, caption, JOptionPane.WARNING_MESSAGE, icon);

Interface is my GUI, "caption" is the title, then I have a warning message, then I have my custom icon.

This might not even be possible with the given info, but I really need to get rid of that OK. Any help would be appreciated.


Solution

  • Why not simply create a JDialog and put your interface object into its contentPane, then pack it and display it. Simple.


    You state:

    Obviously JOptionPane is small, but to do a JDialog I'd have to create a Window and more stuff. The GUI is already created, and I can simply import that into the JOptionPane. Can't do that for a JDialog I believe.

    I'm confused. What do you mean by "the GUI"? Again, if it is a JPanel, again, simply put it into your JDialog.

    For instance if in an ActionListener

    public void actionPerformed(ActionEvent e) {
      // assuming this is being called from within a JFrame named myFrame
      JDialog dialog = new JDialog(myFrame, "Dialog Title", ModalityType.APPLICATION_MODAL);
      dialog.getContentPane().add(interface);
      dialog.pack();
      dialog.setLocationRelativeTo(myFrame);
      dialog.setVisible(true);
    }
    

    Another option is to use the JOptionPane constructor, and create it without showing it, and then convert it to a JDialog as the JOptionPane API shows you how to do, but you may still have the OK or similar button to deal with.