SwingWorker with FileReader

怎甘沉沦 提交于 2019-12-02 15:23:51

问题


I have problem about applied SwingWorker with FileReader and my point is I need to implement FileReader with SwingWorker to make my UI Show the text from the file and this is my code

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

However it does not append anything on the UI textarea

anyone have solution? Thank you


回答1:


Works just fine for me:

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


来源:https://stackoverflow.com/questions/11608822/swingworker-with-filereader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!