import java.awt.Color; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /* Author: James Tam Version: 2015 */ public class MyFrame extends JFrame { private JLabel aLabel; private GridBagLayout aLayout; private GridBagConstraints aConstraint; private JButton left; private JButton right; public MyFrame() { MyWindowListener aWindowListener = new MyWindowListener (); addWindowListener(aWindowListener); // Calling method of super class. aConstraint = new GridBagConstraints(); left = new JButton("LEFT: Press right button."); left.setBackground(Color.lightGray); left.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JButton left = (JButton) e.getSource(); MyFrame aFrame = (MyFrame) left.getRootPane().getParent(); String title = aFrame.getTitle(); aFrame.setTitle("Left pressed"); right.setBackground(Color.green); left.setBackground(Color.lightGray); timeDelay(); aFrame.setTitle(title); } }); right = new JButton("RIGHT: Press left button"); right.setBackground(Color.lightGray); right.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JButton right = (JButton) e.getSource(); MyFrame aFrame = (MyFrame) right.getRootPane().getParent(); String title = aFrame.getTitle(); JButton left = aFrame.getLeft(); aFrame.setTitle("Right pressed"); left.setBackground(Color.green); right.setBackground(Color.lightGray); timeDelay(); aFrame.setTitle(title); } }); aLabel = new JLabel("Simple label"); aLayout = new GridBagLayout(); setLayout(aLayout); // Calling method of super class. addWidget(aLabel,0,0,1,1); addWidget(left,1,0,1,1); addWidget(right,2,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. } public JButton getLeft() { return(left); } public JButton getRight() { return(right); } }