-3

I wrote this code, it allows to select a file and get the filename and its directory:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class NewsReader
{
    static String filename = "";
    static String directory = "";
    public static void main (String... doNotMind)
    {
        open = new FileChooserTest
        FileChooserTest.run (new FileChooserTest(), 250, 110);
    }
}

class FileChooserTest extends JFrame 
{
    private JButton open = new JButton("Open");
    public FileChooserTest() 
    {
        JPanel p = new JPanel();
        open.addActionListener(new OpenL());
        p.add(open);
        Container cp = getContentPane();
        cp.add(p, BorderLayout.SOUTH);
        p = new JPanel();
        p.setLayout(new GridLayout(2, 1));
        cp.add(p, BorderLayout.NORTH);
    }

  class OpenL implements ActionListener 
  {
      public void actionPerformed(ActionEvent e) 
      {
          JFileChooser c = new JFileChooser();
          int rVal = c.showOpenDialog(FileChooserTest.this);
          if (rVal == JFileChooser.APPROVE_OPTION) 
          {
              NewsReader.filename = c.getSelectedFile().getName();
              NewsReader.directory = c.getCurrentDirectory().toString();
          }

          if (rVal == JFileChooser.CANCEL_OPTION) 
          {
              NewsReader.filename = "";
              NewsReader.directory = "";
          }
      }
    }

  public void run(JFrame frame, int w, int h) 
  {
      Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
      setLocation(dim.width/2-getSize().width/2, dim.height/2-getSize().height/2);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(w, h);
      frame.setVisible(true);
    }
}

When I tried to compile it, I got this compile error:

NewsReader.java:12: error: non-static method run(JFrame,int,int) cannot be referenced from a static context
    FileChooserTest.run (new FileChooserTest(), 250, 110);

This error appears often when I'm compiling other programs as well, can you please explain why it's happening and how to resolve it?

Luke Melaia
  • 1,470
  • 14
  • 22
  • Calling FileChooserTest.run() is static reference to the method (you can tell because you're using the type name.) You want to call open.run() (once you get your open object property instantiated and initialized.) Plus you need to read up on static vs. non-static references. – Duston Jan 03 '17 at 20:38

1 Answers1

0

FileChooserTest is the name of the class. You need an instance of the class to use its run method.

Fortunately, you already have one. You created a variable open of that type. So you can just use open.run() and it should be OK.

D M
  • 1,410
  • 1
  • 8
  • 12