Java: can a child kill a parent?

In the snippet below, ParentClass starts the controller, then hides. It would be nice to kill ParentClass on. jMenuItemExitActionPerformed. In retrospect, I should have reversed the relationship between parents and children, but at this point it would be a big change. Is there an easier way?

public class ParentClass extends javax.swing.JFrame {
    private void processC() {
        JFrame controller = new Controller();
        this.setVisible(false);
        ...
public class Controller extends javax.swing.JFrame {
    private void jMenuItemExitActionPerformed(java.awt.event.ActionEvent evt) {                                                   
        System.exit(0);
        ...
+3
source share
3 answers

The easiest way is to pass a reference to the parent, for example:

public class ParentClass extends javax.swing.JFrame {
    private void processC() {
        JFrame controller = new Controller(this);
        this.setVisible(false);
        ...
public class Controller extends javax.swing.JFrame {
    private ParentClass parent;
    public Controller(ParentClass parent) {
        this.parent = parent;
    }
    private void jMenuItemExitActionPerformed(java.awt.event.ActionEvent evt) {                                                   
        parent.exit(); // or whatever
        System.exit(0);
        ...
+2
source

/ - . , , , . , , . .

+1

Adding public static output to ParentClass seems to work.

public class ParentClass extends javax.swing.JFrame { 
    private void processC() { 
        JFrame controller = new Controller(); 
        this.setVisible(false); 
        ... 
    public static void exit() {
        System.exit(0);
  ...
public class Controller extends javax.swing.JFrame { 
    private void jMenuItemExitActionPerformed(java.awt.event.ActionEvent evt) {
        ParentClass.exit(); 
        ... 
+1
source

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


All Articles