I can't seem to get this one right. According to the docs, getTopLevelAncestor() returns:
"Returns the top-level ancestor of this component (either the containing Window or Applet), or null if this component has not been added to any container. "
Seems simple enough, but I can't get it to return anything but null.
Here's some sample code - first a top level container JFrame:
import java.awt.*;
import javax.swing.*;
public class Top extends JFrame {
private MyPanel mp;
public Top() {
super("Test Frame");
mp = new MyPanel();
getContentPane().add(mp);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Top();
}
}
And then a nice panel to fill it:
import java.awt.*;
import javax.swing.*;
public class MyPanel extends JPanel {
private JLabel label;
public MyPanel() {
super(new FlowLayout());
Container topF = this.getTopLevelAncestor();
label = new JLabel();
add(label);
if (topF == null) {
label.setText("Only got null");
} else {
label.setText("Actually got a container ref");
}
}
}
Alas, it keeps throwing me nulls. What am I doing wrong?
TIA,
GMA