2 u012486516 u012486516 于 2015.07.22 09:20 提问

java小问题,百度了好久也没解决。。

错误代码:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at z.TextEdit.actionPerformed(jishiben.java:110)
at java.awt.MenuItem.processActionEvent(Unknown Source)
at java.awt.MenuItem.processEvent(Unknown Source)
at java.awt.MenuComponent.dispatchEventImpl(Unknown Source)
at java.awt.MenuComponent.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
源代码
package z;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.FileFilter;

import static java.awt.event.InputEvent.*;

import java.awt.datatransfer.*;
import java.util.Enumeration;
import java.util.Hashtable;

class jishiben {
public static void main(String args[]) {
TextEdit main = new TextEdit("记事本");
}
}

class TextEdit extends Frame implements ActionListener {
MenuBar m;
Menu m1, m2;
MenuItem xinjian, dakai, baocun, tuichu, jianqie, fuzhi, zhantie, chazhao;
TextArea text;// 文本区
JTextField searchtext;// 搜索文字
JTextField changetext;// 替换文字
String filename;
BufferedReader in;// 缓冲字符输入流
BufferedWriter out;
FileReader read;
FileWriter writer;
Clipboard cb;// 创建剪贴板对象

TextEdit(String s) {
    super(s);
    m = new MenuBar();
    m1 = new Menu("文件");
    xinjian = new MenuItem("新建");
    dakai = new MenuItem("打开");
    baocun = new MenuItem("保存");
    tuichu = new MenuItem("退出");
    m2 = new Menu("编辑");
    jianqie = new MenuItem("剪切");
    fuzhi = new MenuItem("复制");
    zhantie = new MenuItem("粘贴");
    chazhao = new MenuItem("查找与替换");
    text = new TextArea();
    filename = "NoName";

    m1.add(xinjian);
    m1.addSeparator();
    m1.add(dakai);
    m1.addSeparator();
    m1.add(baocun);
    m1.addSeparator();
    m1.add(tuichu);
    m2.add(jianqie);
    m2.addSeparator();
    m2.add(fuzhi);
    m2.addSeparator();
    m2.add(zhantie);
    m2.addSeparator();
    m2.add(chazhao);
    m.add(m1);
    m.add(m2);

    // 剪切
    cb = new Clipboard("nothing");

    setMenuBar(m);
    setSize(300, 400);
    setVisible(true);
    setLocation(400, 200);
    add(text, "Center");

    xinjian.addActionListener(this);
    dakai.addActionListener(this);
    baocun.addActionListener(this);
    tuichu.addActionListener(this);
    jianqie.addActionListener(this);
    fuzhi.addActionListener(this);
    zhantie.addActionListener(this);
    chazhao.addActionListener(this);
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == xinjian) {
        text.setText(" ");
    }

    if (e.getSource() == dakai) {
        // 文件选择组件使用
        JFileChooser jfc1 = new JFileChooser();
        // 设置名字
        jfc1.setDialogTitle("请选择文件......");
        // 默认方式
        jfc1.showOpenDialog(null);
        // 显示
        jfc1.setVisible(true);
        // 得到用户选择的文件路径

        String filename = jfc1.getSelectedFile().getAbsolutePath();
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader(filename);
            br = new BufferedReader(fr);
            // 从文件中读取的文件,显示到text上,
            String s = "";
            String all = "";
            while ((s = br.readLine()) != null) {
                all += s + "\r\n";
            }
            // 放到text
            text.setText(all);

        } catch (Exception e2) {
            // TODO: handle exception
            e.paramString();
        } finally {
            try {
                br.close();
                fr.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }
    if (e.getSource() == baocun) {
        // 出现保存对话框
        JFileChooser jfc = new JFileChooser();
        jfc.setDialogTitle("另存为...");
        // 按照默认的方式显示
        jfc.showSaveDialog(null);
        jfc.setVisible(true);
        String file = jfc.getSelectedFile().getAbsolutePath();

        // 准备写入到指定的文件中
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            bw.write(this.text.getText());

        } catch (Exception e2) {
            e.paramString();
            // TODO: handle exception
        } finally {
            try {
                bw.close();
                fw.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }
    if (e.getSource() == tuichu) {
        System.exit(0);
    }

    if (e.getSource() == jianqie) {
        String s = text.getSelectedText();
        // 创建能传输指定 String 的 Transferable。
        StringSelection select = new StringSelection(s);
        // 把selecct内容放到剪贴板中
        cb.setContents(select, null);
        // 清零
        text.replaceRange("", text.getSelectionStart(),
                text.getSelectionEnd());
    }

    if (e.getSource() == fuzhi) {
        String s = text.getSelectedText();
        StringSelection select = new StringSelection(s);
        cb.setContents(select, null);
    }

    if (e.getSource() == zhantie) {
        String s = "";
        // 得到剪贴板的内容
        Transferable t = cb.getContents(null);
        try {
            if (t != null// isDataFlavorSupported返回此对象是否支持指定的数据 flavor
                    && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                // 因为原系的剪贴板里有多种信息, 如文字, 图片, 文件等
                // 先判断开始取得的可传输的数据是不是文字, 如果是, 取得这些文字

                s = (String) t.getTransferData(DataFlavor.stringFlavor);
                // 同样, 因为Transferable中的DataFlavor是多种类型的,
                // 所以传入DataFlavor这个参数, 指定要取得哪种类型的Data.
            }
        } catch (UnsupportedFlavorException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        text.insert(s, text.getCaretPosition());

    }
    if (e.getSource() == chazhao) {
        new chaz(text);
    }
}

}

class chaz extends Dialog implements ActionListener {
String wenben;
TextArea ta;
boolean flg = false;
int len;
int start = 0;
int k = 0;

Label find1 = new Label("查找的字符串");
Label replace1 = new Label("替代的字符串");
TextField find2 = new TextField(10);
TextField replace2 = new TextField(10);
Button find3 = new Button("查找");
Button replace3 = new Button("替换");

public chaz(TextArea ta) {
    super(new Frame(), "查找或替换");

    this.ta = ta;
    Panel pan1 = new Panel();
    Panel pan2 = new Panel();
    pan1.add(find1);
    pan1.add(find2);
    pan1.add(find3);
    pan2.add(replace1);
    pan2.add(replace2);
    pan2.add(replace3);
    setResizable(false);
    setBounds(200, 200, 300, 100);
    add(pan1, BorderLayout.NORTH);
    add(pan2, BorderLayout.SOUTH);

    find3.addActionListener(this);
    replace3.addActionListener(this);

    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            chaz.this.dispose();
        }
    });
    setVisible(true);
}

public void actionPerformed(ActionEvent e) { // 查找替换事件处理方法
    String ske = find2.getText();// 要查询的文字
    wenben = ta.getText();
    String tke = replace2.getText();// 要替换的文字
    if (e.getSource() == find3) {
        find3.setLabel("完毕!");
        if (ske != null) {
            len = ske.length();
            start = wenben.indexOf(ske, k);
            k = start + len;
            ta.select(start, start + len);
            flg = true;
            if (start == -1) {
                JOptionPane.showMessageDialog(null, "已到文件尾部!", "提示",
                        JOptionPane.INFORMATION_MESSAGE);
                start = 0;
                k = 0;
                flg = false;
            }
        }
    } else if (e.getSource() == replace3) {
        if (flg) {
            ta.replaceRange(tke, start, start + len);
            flg = false;
        }
    }
}

}

7个回答

danielinbiti
danielinbiti   Ds   Rxr 2015.07.22 09:32
能运行,就打开后关闭的时候报错了
 jfc1.setVisible(true);
        // 得到用户选择的文件路径
        if(jfc1.getSelectedFile()==null){//如果没有选择文件,需要判断
            return;
        }
        String filename = jfc1.getSelectedFile().getAbsolutePath();
yuke198907
yuke198907   2015.07.22 09:28

z.TextEdit.actionPerformed(jishiben.java:110)这个地方发生空指针了

tongyi55555
tongyi55555   2015.07.22 09:42

danielinbiti说的对,你这个问题其实很好解决的,在你jishiben程序的第110行出现了空指针,你定位一下哪个变量是空就知道了。最主要的问题是你选择的文件为空时会报错。

qq_28314431
qq_28314431   2015.07.22 10:03

空指针异常 应该是没有把文件读进来

strutce
strutce   Ds   Rxr 2015.07.22 10:19

String filename = jfc1.getSelectedFile().getAbsolutePath();
代码中2处加上判null
if(jfc.getSelectedFile()==null){
return;
}

cuiwei1026522829
cuiwei1026522829   Ds   Rxr 2015.07.22 10:40

z.TextEdit.actionPerformed(jishiben.java:110)
重点看这行,之所以搜不到,也是因为具体问题具体分析吧,我当初也是搜,没有太多想,后来才明白要多想

weixin_29501135
weixin_29501135   2015.07.27 09:02

点击右下角的+,可以添加常用短语。

Csdn user default icon
上传中...
上传图片
插入图片