Question

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??

Was it helpful?

Solution

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()

OTHER TIPS

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);

    .....

  }

}

You could have the JFrame implement ActionListener and add it to the button using addActionListener.

I like to put a 'launch()' method on all my frames / dialogs. With the right modality it can return a result.

Example of return value from dialog:

private static class MyDialog extends JDialog {
    String result;
    private JButton btnOk = new JButton("OK");

    public MyDialog() {
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setModalityType(ModalityType.APPLICATION_MODAL);

        add(btnOk);
        btnOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                result = "Ok";
                setVisible(false);
            }
        });
    }

    public String launch() {
        result = "Cancel";
        pack();
        setVisible(true);
        return result;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top