在组件之间传递值 [英] Passing a value between components

查看:106
本文介绍了在组件之间传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JDialog ,它调用 AsbtractAction ,它会调出 JFileChooser 所以用户可以选择一个目录。这些都是单独的类。从 JFileChooser 传递值的正确方法是什么,所以我可以在 JDialog 中显示目录的路径?

I have a JDialog which calls an AsbtractAction which brings up a JFileChooser so the user can select a directory. These are all separate classes. What is the proper way of passing a value from the JFileChooser so I can display the path to the directory in the JDialog?

编辑:更新了问题。

推荐答案

这是一个不完整的例子,但我想可以给你一个如何实现你需要的想法。重要的是引用你想要选择的属性,如 YourDialog.this.selectedFile = file;

This is an incomplete example but I guess can give you an idea of how to achieve what you need. The important bit is to reference the property where you want the selection back like YourDialog.this.selectedFile=file;

请参阅下文如何将其放入代码中:

See below how to place it in the code:

   public class YourDialog extends JDialog implements ActionListener {
          protected File selectedFile=null;
          //Constructor
          public YourDialog(JFrame frame, boolean modal, String message) {
                //... create button and added to the panel
                someButton.addActionListener(new AbstractAction {
                    public void actionPerformed(ActionEvent e) {
                            final JFileChooser fc = new JFileChooser();
                            int returnVal = fc.showOpenDialog(YourDialog.this);
                            if (returnVal == JFileChooser.APPROVE_OPTION) {
                                File file = fc.getSelectedFile();

                                // HERE IS THE TRICK I GUESS !!
                                YourDialog.this.selectedFile=file;
                            }
                    }

                });
          }
    }

我希望它有所帮助并抱歉没有发布完整版例如。

I hope it helps and sorry for not posting a full example.

编辑

本质上我们没有将任何参数传递给AbstractAction。事实是,AbstractAction可以通过访问类似 YourDialog.this.somePropertyOrMethod 来访问调用者的任何非私有属性。这是因为 AbstractAction YourDialog 类的匿名类。

In essence we are not passing any parameters to the AbstractAction. The fact is that the AbstractAction can access any non-private properties of the "caller" by accessing like YourDialog.this.somePropertyOrMethod. This is because the AbstractAction is an anonymous class of YourDialog class.

这篇关于在组件之间传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆