Quiz J4-1 | CS 2113 Software Engineering - Spring 2021

Quiz J4-1

Submit your answers via this Google Form

Question 1

Consider the class that extends JFrame below

class ParentJFrame extends JFrame {
    private JFrame[] frames = new JFrame[5];

    private JFrame[] frames = new JFrame[5];

    public ParentJFrame() {
        for (int i = 0; i < 5; i++) {
            JFrame f = new JFrame();
            f.setTitle("Quiz Child" + i);
            f.setSize(100, 100);
            // Make windows appear on a diagonal line
            f.setLocation(100 * i, 100 * i);
            f.addWindowListener(new ChildAdapter());
            f.setVisible(true);
            frames[i] = f;
        }
        this.addWindowListener(new ParentAdapter());
    }

    private static class ChildAdapter extends WindowAdapter {
        // Called when window closes
        @Override
        public void windowClosing(WindowEvent e) {
            System.out.println("Closed!");
        }

    }
    
    private static class ParentAdapter extends WindowAdapter {

        @Override
        public void windowClosing(WindowEvent e) {
            System.out.println("Parent Closed!");
        }

    }

}

What’s the output of the below program when we close the ParentJFrame immediately after it appears?

    public static void main(final String args[]) {
        ParentJFrame frame = new ParentJFrame();
        frame.setTitle("Quiz Parent");
        frame.setSize(100, 100);
        frame.setLocation(100, 100);
        frame.setVisible(true);
    }

Question 2

If we do not close the parent, but instead close all the children windows, what is the output?

Question 3

Now we add this line to the end of main from the program in question 1:

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // makes it so that closing window exits program

And then we close the parent, what happens?

Question 4

Now we close the children windows, and then the parent, what’s the output?

Question 5

Finally we change the constructor of ParentJFrame to the below:

    public ParentJFrame() {
        for (int i = 0; i < 5; i++) {
            JFrame f = new JFrame();
            f.setTitle("Quiz " + i);
            f.setSize(100, 100);
            f.setLocation(100 * i, 100 * i);
            f.addWindowListener(new ChildAdapter());
            f.setVisible(true);
            // Line that was added
            // *******
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // makes it so that closing window exits program
            // *******
            frames[i] = f;

        }
        this.addWindowListener(new ParentAdapter());
    }

And then close a child window, what’s the output?