2
\$\begingroup\$

I want to open a file contents using swing. For this I used the SwingWorker class. This application took more time (more than a minute) to load a large file (nearly 40MB). I want to improve the performance of the open file contents.

public class OpenDemo extends javax.swing.JFrame {
JTextPane textPane;
JScrollPane scrollPane;
int i=0;
public OpenDemo() {
    initComponents();
    textPane=new JTextPane();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    tp = new javax.swing.JTabbedPane();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    open = new javax.swing.JMenuItem();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jMenu1.setText("File");

    open.setText("Open");
    open.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            openActionPerformed(evt);
        }
    });
    jMenu1.add(open);

    jMenuBar1.add(jMenu1);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        

private void openActionPerformed(java.awt.event.ActionEvent evt) {                                     
    JFileChooser fileChooser=new JFileChooser();
    int result = fileChooser.showOpenDialog(this);
                    if (result==JFileChooser.APPROVE_OPTION) {
                        File file = fileChooser.getSelectedFile();
                        try {
                            textPane.setPage(file.toURI().toURL());
                        } catch(Exception e) {
                            e.printStackTrace();
                        }
                    }
      JInternalFrame internalFrame = new JInternalFrame("",true,true); 
      i++;
      internalFrame.setName("Doc "+i);
      tp.add(internalFrame);
      scrollPane=new JScrollPane(textPane);
      internalFrame.add(scrollPane);
      internalFrame.setVisible(true);
      textPane.setCaretPosition(0); 

}                                    

public static void main(String args[]) {
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new OpenDemo().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JTabbedPane tp;
// End of variables declaration                   

}
\$\endgroup\$
4
  • \$\begingroup\$ I had indent my code correctly.Please check it once. \$\endgroup\$ Aug 22, 2014 at 8:28
  • \$\begingroup\$ I've also reversed the code changes. Please don't update the original code based on answers. \$\endgroup\$
    – Jamal
    Aug 26, 2014 at 5:31
  • \$\begingroup\$ Please check it once,how to load files quickly in JTextPane.I have tried this one for more than two weeks.provide any ideas. \$\endgroup\$ Aug 26, 2014 at 5:50
  • \$\begingroup\$ Please check it once again.This is very tough task for me.Anybody provide the solution for this. \$\endgroup\$ Aug 28, 2014 at 11:15

1 Answer 1

1
\$\begingroup\$

You can stop the inner loop when the action is canceled by checking isCanceled() inside the while in doInBackground and returning null.

You don't clean up the buffered reader after you are done reading from it.

There is no need to let the Stringbuilder out of doInBackground() (and doing so invites bad access, declare it in doInBackground().

You can initialize the StringBuilder with an initial capacity equal to the length of the file to minimize reallocations.

  @Override
  public StringBuilder doInBackground() throws IOException, InterruptedException {
    int lineNumber = 0;
    String line;
    StringBuilder text = new StringBuilder((int)file.length());
    BufferedReader br=null;
    try{
        br = new BufferedReader(new FileReader(file));
        while ((line = br.readLine()) != null) {
          if(isCancelled())
              return null;
          lineNumber++;
          text.append(line);
          text.append("\n");
          ProgressData data = new ProgressData();
          data.number = lineNumber;
          data.line = line;
          publish(data);
        }
    }finally{
        if(br!=null)br.close();
    }
   return text;
 }

The only feature you use from textReader is its cancel ability, so you can just declare it as a Future<StringBuilder>. Then you can keep the ProgressData class as a static inner class of TextReader. Conversely you can declare textReader as a TextReader and also keep ProgressData as a static inner class.

\$\endgroup\$
2
  • \$\begingroup\$ Hi,I edit my code followed by your suggestions.But,this time also taking time to load large file contents.It has taken minimum a minute time to load.Please check it once.Thank you for your suggestions. \$\endgroup\$ Aug 25, 2014 at 5:57
  • \$\begingroup\$ I edit my code without SwingWorker classs.But,This time I remove some code to read the contents of a file.Just I called a single method(setPage()) available in textpane.But,this time also taking time to load large files.check it once. \$\endgroup\$ Aug 26, 2014 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.