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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With