managing parent frame from child frame on java swing

21,161

Solution 1

Pass in a reference to the parent frame when you create (or display) the child frame. This will require an overloaded constructor or display method.

Once the child has the reference, it can of course call any method that the parent exposes as public, like UpdateDate()

Solution 2

As of Java 1.3

public class MyPanel extends JPanel
{

  public MyPanel() {

    ....

    JButton cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          // <<<< HERE'S THE INTERESTING BIT >>>>
          javax.swing.SwingUtilities.getWindowAncestor(MyPanel.this).dispose();
        }
      }
    );
    add(cancelButton);

    .....

  }

}
Share:
21,161
JuanDeLosMuertos
Author by

JuanDeLosMuertos

Software engineer

Updated on November 26, 2020

Comments

  • JuanDeLosMuertos
    JuanDeLosMuertos over 3 years

    I have a jframe (parent) which creates an input frame (child) where I get some parameter.

    In the "child" frame I have "ok" and "cancel" buttons.

    When "ok" button is pressed, the parent frame needs to be updated with new data.

    What is the best way to do that??

  • JuanDeLosMuertos
    JuanDeLosMuertos about 15 years
    this I the solution I'm using, there is no cleanest way?
  • rachana
    rachana almost 10 years
    Thank you so much.Solved my issue :)
  • FuriousFolder
    FuriousFolder over 8 years
    This is much cleaner. +1