import java.awt.Component; import java.awt.Container; import java.awt.Insets; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JFrame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /* Author: James Tam Version: March 29, 2021 */ public class MyFrame extends JFrame { public static final int PADDING = 2; private GridBagLayout aLayout; private GridBagConstraints aConstraint; private JButton aButton; private JLabel aLabel; public MyFrame () { MyWindowListener aWindowListener = new MyWindowListener (); addWindowListener(aWindowListener); // Calling method of super class. aButton = new JButton("Press button for a surprise"); aConstraint = new GridBagConstraints(); aConstraint.insets = new Insets(PADDING,PADDING,PADDING,PADDING); aButton.addActionListener(new ActionListener() //Creating anonymous object in parameter list { //Start of anonymous class definition public void actionPerformed(ActionEvent e) { Object anObject = e.getSource(); Container aContainer; JButton aButton; MyFrame aFrame; if (anObject instanceof JButton) { aButton = (JButton) anObject; aContainer = aButton.getRootPane().getParent(); if (aContainer instanceof JFrame) { aFrame = (MyFrame) aContainer; String windowText = aFrame.getTitle(); aFrame.setTitle("Button pressed"); timeDelay(); aFrame.setTitle(windowText); makePopup(); } } } //End: actionPerformed() public void makePopup() { JDialog aDialog; JLabel aLabel; JButton aButton; aDialog = new JDialog(); aDialog.setLayout(null); aDialog.setBounds(200,200,400,200); aLabel = new JLabel("Don't press the button"); aButton = new JButton("Non functional"); aLabel.setBounds(100,0,150,20); aButton.setBounds(100,50,150,20); aDialog.add(aLabel); aDialog.add(aButton); aDialog.setVisible(true); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); } }); //End definition of anonymous class, parameter list aLabel = new JLabel("Simple label"); aLayout = new GridBagLayout(); setLayout(aLayout); // Calling method of super class. addWidget(aLabel, 0, 0, 1, 1); addWidget(aButton, 1, 0, 1, 1); } private void timeDelay () { try { Thread.sleep(3000); } catch (InterruptedException e) { System.out.println("Problem with pasuing of the program"); } } public void addWidget (Component widget, int x, int y, int w, int h) { aConstraint.gridx = x; aConstraint.gridy = y; aConstraint.gridwidth = w; aConstraint.gridheight = h; aLayout.setConstraints (widget, aConstraint); add(widget); // Calling method of super class. } }