Re: How to get reference for JFrame
Coolm@x wrote:
Hello,
I want to ask for an example. I want to run JDialog from JMenuItem. I
have JFrame in one file and JDialog in another. As far as I know I must
pass frame-parent as argument to JDialog. Examples which I found were
similar to:
JFrame frame = new JFrame();
JDialog dialog = new JDialog(frame (...)
Code is in one class, so there is no problem. I don't know how to pass
argument in this:
....
Is there any method to get jFrame parent? Also, is this code correct:
JDabout about = new JDabout(?);
If you're able to obtain the component where the ActionEvent originated
from, you can obtain the frame where the component lives in, too.
class Util {
// ...
public static Frame getFrameAncestor(Component c) {
Frame frame = null;
Window w = SwingUtilities.getWindowAncestor(c);
if ( w instanceof Frame )
frame = (Frame) w;
return frame;
}
}
(Of course, you can rewrite the above method to be more Frame specific
by walking up the component hierarchy)
Fortunately, the ActionEvent provides it's source which often is-a
component. Therefore you can do something like this:
public void actionPerformed(ActionEvent e) {
Frame frame = null;
Object source = e.getSource();
if ( source != null && source instanceof Component ) {
frame = Util.getFrameAncestor((Component) source);
}
// it's perfectly legal to pass the null-reference to JDialog.
JDabout dlg = new JDabout(frame);
}
HTH
Michael