SwingWorker的用的FileReader(SwingWorker with FileRead

2019-07-30 13:45发布

我的问题关于应用的SwingWorker用的FileReader和我的观点是我需要实现的FileReader与SwingWorker的,使我的UI显示从文件中的文本,这是我的代码

class Read1 extends SwingWorker<String,String>{
    protected Void doInBackground() throws Exception{
        FileReader read = new FileReader("msg.txt");
        BufferedReader in = new BufferedReader(read);
        String s;
        s=in.readLine();
        System.out.println(s);
        return s;
    }
   protected void done()
    {
      try{
       String show;
       show=get();
       textArea.append(show);}catch(Exception e){}}

 public static void main(String args[]) {
   Read1 r = new Form().new Read1();
   r.execute();

然而,它并没有对UI textarea的任何附加

人有解决办法吗? 谢谢

Answer 1:

作品对我蛮好:

public class Reader extends SwingWorker<List<String>, String> {

    protected List<String> doInBackground() throws Exception {

        ArrayList<String> lstText = new ArrayList<String>(25);

        BufferedReader in = null;
        try {

        FileReader read = new FileReader("Scanner.txt");
        in = new BufferedReader(read);
        String s = null;

        while ((s = in.readLine()) != null) {

            lstText.add(s);
            publish(s);

        }

        } finally {


            try {

                in.close();

            } catch (Exception e) {
            }
        }

        return lstText;

    }

    @Override
    protected void process(List<String> chunks) {

        for (String text : chunks) {

            fldText.append(text + "\n");

        }

    }

    @Override
    protected void done() {
    }
}


文章来源: SwingWorker with FileReader