Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

java - Passing a value between components

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?

Edit: Updated the question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Edit

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...