2017-01-03 31 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(),它應該是確定的。

相關問題