错误:没有为FileDialog找到合适的构造函数(Notepad,String,int)

时间:2017-06-11 08:50:20

标签: java

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

    }
    // [...]
}

我明白了:

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

2 个答案:

答案 0 :(得分:1)

FileDialog fd=new FileDialog(this,"Open File",FileDialog.LOAD);错误。

第一个参数必须是Frame,即父项。也许用:

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

Plz看看这个:https://docs.oracle.com/javase/7/docs/api/java/awt/FileDialog.html

答案 1 :(得分:1)

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

您使用this作为第一个参数,而this指的是您当前正在处理的类的实例,因此指向Notepad。例如,如果您使用代码中的其他位置:

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

然后this引用np。你应该使用

FileDialog fd=new FileDialog(f,"Open File",FileDialog.LOAD);
编辑:另一位用户在我之前得到了一个非常相似的答案,对不起