Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate JDialog from JPanel

Tags:

java

swing

I've got a JPanel, which I want to respond to a mouse click and then open a JDialog. The JDialog constructor needs an instance of JFrame and not JPanel - how do I work around this?

like image 652
EngineerBetter_DJ Avatar asked May 09 '12 18:05

EngineerBetter_DJ


3 Answers

You should really try to attach the JDialog to a parent Dialog or Frame, especially if you want it modal (by passing a parent Window, the dialog will be attached to your Window and bringing the parent will bring the child dialog as well). Otherwise, the user experience can really go wrong: lost dialogs, blocking windows without seeing the modal dialog, etc...

To find your JPanel parent Window, all you need is this code:

JPanel panel = new JPanel();
Window parentWindow = SwingUtilities.windowForComponent(panel); 
// or pass 'this' if you are inside the panel
Frame parentFrame = null;
if (parentWindow instanceof Frame) {
    parentFrame = (Frame)parentWindow;
}
JDialog dialog = new JDialog(parentFrame);
...

If you don't know if you are in a Frame or Dialog, make the "instanceof" test for both classes.

like image 169
Guillaume Polet Avatar answered Nov 11 '22 12:11

Guillaume Polet


Using the parameter free constructor will make the dialog owner-less. I think that the best thing to do would be to make the Frame that owns your Panel the owner of the dialog.

By that, I mean that you should use the getParent() from your JPanel to find its owner and then send this object found as the owner of your JFrame.

A crude code for that would be

java.awt.Container c = myPanel.getParent();  
while (!(c instanceof javax.swing.JFrame) && (c!=null)) {  
        c = c.getParent();  
}  
if (c!=null) { 
    JFrame owner=(javax.swing.JFrame) c;  
    JDialog myDialog=new JDialog(owner);
}

I have not tested this code, but it is good enought for you to understand the idea.

like image 3
rlinden Avatar answered Nov 11 '22 12:11

rlinden


If you decided to go with a JOptionPane, you could add a MouseListener to the JPanel with a mouseAdapter inner class to handle mouseClicked events. You would have to declare the panel final in order to access the panel from within the inner class.

final JPanel testPanel = new JPanel();

testPanel.addMouseListener(new MouseAdapter(){
     public void mouseClicked(MouseEvent e)
     {           
         JOptionPane.showMessageDialog(testPanel,"Title","InformationMessage",JOptionPane.INFORMATION_MESSAGE);

    }});//end of mouseClicked method
like image 2
Itchy Nekotorych Avatar answered Nov 11 '22 11:11

Itchy Nekotorych