views:

38

answers:

1

Hi folks,

I intend to implement a Swing application which keeps all its JComponents within the main application window JFrame. It seems like clunky procedural code to give all my JPanel constructors a parameter referring to the JFrame. So some research uncovered SwingUtilities.getAncestorOfClass, which looked like the solution. But I cannot understand why it returns null when I try to use it to get a reference to the JFrame in my JPanel code.

To give you an idea, here is code for the main JFrame, which also creates a ViewPanel and plonks that in the JFrame:

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class SDA {
    public static void main (String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                SDAMainViewPanel sdaMainViewPanel = new SDAMainViewPanel();
                JFrame frame = new JFrame("SDApp");
                frame.setSize(400, 400);
                frame.setContentPane(sdaMainViewPanel);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                    
                frame.setLocationRelativeTo(null);                
                frame.setVisible(true);
            }
        });
    }
}

Here is my code for the ViewPanel, which, when you press the button "Try Me", results in a NullPointerException, because the call to SwingUtilities.getAncestorOfClass for the ViewPanel is a null call.

import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;

public class SDAMainViewPanel extends JPanel {

    public SDAMainViewPanel() {
        initComponents();
    }

    private void initComponents() {
        getAncClass = new JButton("Try me");
        // This is null even though there IS an Ancestor JFrame!?!?
        final JFrame parent = (JFrame)SwingUtilities.getAncestorOfClass(JFrame.class, this);
        getAncClass.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {                
                parent.getContentPane().removeAll();
            }
        });
        add(getAncClass);
    }

    private JButton getAncClass;
}

Thanks in advance if you can assist with this question.

+1  A: 

SDAMainViewPanel's constructor calls initComponents, but it gets called before sdaMainViewPanel has been added to a JFrame. You can:

  • Call initComponents only after the SDAMainViewPanel has been added to the JFrame.
  • Get the parent frame each time the ActionListener is called:

    public void actionPerformed(ActionEvent ae) {
        JFrame parent = (JFrame)SwingUtilities.getAncestorOfClass(JFrame.class, SDAMainViewPanel.this);
        parent.getContentPane().removeAll();
    }
    
lins314159
Many thanks. +1 for the accuracy of the options given. Hopefully this will help other Java folks as well.
Arvanem