Java Swing main JFrame: why does SwingUtilities.getAncestorOfClass return null?

I intend to implement a Swing application that saves all of its JComponents in the main window of the JFrame application. It seems like a clumsy procedural code gives all my JPanel constructors a parameter related to JFrame. Therefore, in some studies, SwingUtilities.getAncestorOfClass was discovered, which looked like a solution. But I can’t understand why it returns null when I try to use it to get a JFrame reference in my JPanel code.

To give you an idea, here is the code for the main JFrame, which also creates the ViewPanel and plonks 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);
            }
        });
    }
}

ViewPanel, " " NullPointerException, SwingUtilities.getAncestorOfClass ViewPanel - .

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

, .

+3
1

SDAMainViewPanel initComponents, , sdaMainViewPanel JFrame. :

  • initComponents SDAMainViewPanel JFrame.
  • ActionListener:

    public void actionPerformed(ActionEvent ae) {
        JFrame parent = (JFrame)SwingUtilities.getAncestorOfClass(JFrame.class, SDAMainViewPanel.this);
        parent.getContentPane().removeAll();
    }
    
+3

Source: https://habr.com/ru/post/1763967/


All Articles