2017-06-11 34 views
-2
import java.awt.*; 
import java.awt.event.*; 
import java.io.*; 

class Notepad implements ActionListener { 
    Frame f; 
    MenuBar mb; 
    Menu m1, m2; 
    MenuItem nw, opn, sve, sveas, ext, fnd, fr; 
    TextArea t; 

    // [...Constructor removed...] 

    public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == nw) { 
      t.setText(" "); 
     } else if (e.getSource() == opn) { 
      try { 
       FileDialog fd = new FileDialog(this, "Open File", FileDialog.LOAD); // <- Does not compile 
       fd.setVisible(true); 
       String dir = fd.getDirectory(); 
       String fname = fd.getFile(); 
       FileInputStream fis = new FileInputStream(dir + fname); 
       DataInputStream dis = new DataInputStream(fis); 
       String str = " ", msg = " "; 
       while ((str = dis.readLine()) != null) { 
        msg = msg + str; 
        msg += "\n"; 
       } 
       t.setText(msg); 
       dis.close(); 
      } catch (Exception ex) { 
       System.out.print(ex.getMessage()); 
      } 
     } 

    } 
    // [...] 
} 

我得到:錯誤:發現的FileDialog(記事本,字符串,整數)沒有合適的構造

error: no suitable constructor found for FileDialog(Notepad,String,int) 
     FileDialog fd=new FileDialog(this,"Open File",FileDialog.LOAD); 

回答

1
FileDialog fd=new FileDialog(this,"Open File",FileDialog.LOAD); 

您使用this作爲第一個參數,並this是指當前正在工作的類的實例,所以一個Notepad。例如,如果你在代碼中使用,別的地方:

Notepad np = new Notepad(); 
//... 
np.actionPerformed(ae); //ae is an ActionEvent 

然後thisnp。您應該使用

FileDialog fd=new FileDialog(f,"Open File",FileDialog.LOAD); 

編輯:另一個用戶在我之前有一個非常類似的回答,不好意思

相關問題