2017-01-03 27 views
-3

我写了这个代码中引用,它允许选择一个文件,获取文件名和目录:非静态方法运行(JFrame中,INT,INT)不能从静态上下文

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

当我试图编译它,我得到这个编译错误:

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

当我编译其他程序,以及,你可以请解释为什么它的发生,以及如何解决它经常出现此错误?

+0

调用FileChooserTest.run()是方法的静态引用(因为您使用的是类型名称,所以可以说明)。您想调用open.run()(一旦获得了打开的对象属性实例化并初始化后。 )另外你需要阅读静态和非静态引用。 – Duston

回答

0

FileChooserTest是该类的名称。你需要一个类的实例来使用它的run方法。

幸运的是,你已经有一个。您创建了该类型的变量open。所以你可以使用open.run(),它应该是确定的。

相关问题