在java swing上从子框架管理父框架

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/573378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:22:22  来源:igfitidea点击:

managing parent frame from child frame on java swing

javaswingeventsjframejbutton

提问by Giancarlo

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

我有一个 jframe(父),它创建一个输入框架(子),在那里我得到一些参数。

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

最好的方法是什么?

采纳答案by colithium

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

一旦子级有了引用,它当然可以调用父级公开的任何方法,例如 UpdateDate()

回答by Tom Martin

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

您可以让 JFrame 实现 ActionListener 并使用 addActionListener 将其添加到按钮。

回答by corlettk

As of Java 1.3

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

    .....

  }

}

回答by Peter L

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

我喜欢在我的所有框架/对话框上放置一个“launch()”方法。使用正确的方式,它可以返回结果。

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