Creating JDialog from JPanel

I have JPanelone that I want to respond to with a mouse click, and then open JDialog. The constructor JDialogneeds an instance JFrame, not JPanel- how do I get around this?

+5
source share
4 answers

You really should try connecting JDialog to the parent dialog or frame, especially if you want it to be modal (by passing the parent window, the dialog will be attached to your window and casting the parent will result in the dialog of the child). Otherwise, the user interface can really go wrong: lost dialogs, blocking windows without viewing a modal dialog, etc.

JPanel, :

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);
...

, , "instanceof" .

+7

. , Frame, , .

, getParent() JPanel, , , JFrame.

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);
}

, .

+3

JOptionPane, MouseListener JPanel mouseAdapter mouseClicked. , .

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
+2

, :

JDialog dialog = new JDialog();

If you want to make the dialog modal, perhaps you can get a static link to your main JFrame, something like:

JDialog dialog = new JDialog(MyMainJFrame.getInstance());
+1
source

All Articles