Sin5k4
Sin5k4

Reputation: 1626

Calling a variable from another method

i'm quite new in eclipse and having a problems with calling variables from other methods,such as:

    btnNewButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {

            final JFileChooser fc = new JFileChooser();
            int returnVal = fc.showDialog(fc, null);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File prnfile = new File(fc.getSelectedFile().toString());

            }

        }

    });
    btnNewButton.setBounds(54, 164, 89, 23);
    frame.getContentPane().add(btnNewButton);

    JButton btnNewButton_1 = new JButton("print");
    btnNewButton_1.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {


              File file = new File(prnfile);
                int ch;
                StringBuffer strContent = new StringBuffer("");
                FileInputStream fin = null;
                try {
                  fin = new FileInputStream(file);
                  while ((ch = fin.read()) != -1)
                    strContent.append((char) ch);
                  fin.close();
                } catch (Exception e1) {
                  System.out.println(e);
                }



    });
    btnNewButton_1.setBounds(257, 164, 89, 23

Now,how can i call "prnfile" from the other method?Normally i would create a public object in c# but it doesnt work in Eclipse,so i dunno where to go (being a complete noob :) )

Upvotes: 0

Views: 2544

Answers (3)

nexus
nexus

Reputation: 2937

I guess you mean access your object and that has nothing to do with eclipse.

Your object prnfile is inside an anonymous class. Define your variable outside the anonymous class and you do fine.

Upvotes: 1

John Snow
John Snow

Reputation: 5334

What you need to do is to lift out prnFile refrence so it becomes a global variable. As it is written now prnFile is only a local variable and you will not be able to see that variable in another metod and it will be collected by the GC after it's created. So take this part:

File prnfile = new File(fc.getSelectedFile().toString());

and move File prnFile; outside of your method. Inside the the first listener you only call prnFile= new File(fc.getSelectedFile().toString()); and now you will be able to get the value stored inside prnFile from your "print listener"

Upvotes: 3

Chandra Sekhar
Chandra Sekhar

Reputation: 19502

prnfile is a local variable of the if block of mouseClicked, so when control comes out of that if block, the prnfile is garbage collected and its reference is gone. so you cannot access that from outside that if block.

Upvotes: 1

Related Questions