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");
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;
}
, .