Loading set of text into JText area

Posted on 2004-04-19
Last Modified: 2012-06-22
I have a set of text to load up into the JTEXT area. The text are in .txt format. When I am loading the file from the format, into the JTEXT area, my program crash. It is able to compile, but crash, it always shows an out of bound exception error.

Can anyone help? I have attached the code for reference. Thanks.

      private void PrintQuestion(){
            String [] Questions = questions.getQuestion();
            questionarea.setMargin(new Insets(0,100,0,15));
            for (int i=0; i<questions.getQuestion().length; i++){
                  questionarea.append("\n" + Questions[i]);

I have also attached a copy of the text file.>>

Read the following piece of code carefully
public abstract class AbstractClass
     public AbstractClass()
          System.out.println("this is an abstract class constructor!");

     public void aMethod()
          System.out.println("This is in the method in the abstract class");

Attempting to compile and run the code will cause
1: Compiler error - the class cannot be declared as abstract as it does not have any unimplemented methods.
2: Compiler error - the method AbstractClass does not have a valid return type.  
3: Compiler error - abstract classes cannot have constructors.
4: No compiler error - the class is practically not an abstract class and can be instantiated.
5: No compiler error - the class cannot be instantiated directly. It has to be extended to an non-abstract class. The constructors of the extended class will call the constructor of the abstract class (implicitly or explicitly).


Read the following code carefully.

public class AStringQuestion
    static String s1;
    static String s2;
    public static void main(String args[])
         s2 = s1+s2;

1:Will cause a compilation error.
2:Will compile successfully and print nullnull on the screen.
3:Runtime Execption - NullPointerException in the 2nd line of the main method.
4:Will compile successfully and print an empty line on the screen.
5:Will compile successfully and print nothing on the screen.




Question by:cwtang
LVL 92

Expert Comment

ID: 10865271
tyou call questions.getQuestion() multiple times

     private void PrintQuestion(){
          String [] Questions = questions.getQuestion();
          questionarea.setMargin(new Insets(0,100,0,15));
          for (int i=0; i<Questions.length; i++){
               questionarea.append("\n" + Questions[i]);
LVL 15

Expert Comment

ID: 10865276
Can you post your whole codes ?
LVL 23

Accepted Solution

rama_krishna580 earned 500 total points
ID: 10874768
Hi You can check this...


Suppose that you'd like to read a large text file into a Swing
text area, using either a JTextArea or a JTextPane object. Are
there any efficiency issues to consider in this operation?

To find out, you can set up a test program that uses to read in a text file into a text area. Then
experiment. Run the program specifying first a JTextArea and then
a JTextPane as the target for the text, and compare the program
running times. Here's a program you can use to run the test:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;

    public class ReadDemo {

        // read the file into the pane

        static void readin(String fn, JTextComponent pane) {
            try {
                FileReader fr = new FileReader(fn);
      , null);
            catch (IOException e) {

        public static void main(String args[]) {
            final JFrame frame = new JFrame("Read Demo");
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {

            // set up the text pane, either a JTextArea or JTextPane

            final JTextComponent textpane = new JTextArea();
            //final JTextComponent textpane = new JTextPane();

            // set up a scroll pane for the text pane

            final JScrollPane pane = new JScrollPane(textpane);
            pane.setPreferredSize(new Dimension(600, 600));

            // set up the file chooser

            String cwd = System.getProperty("user.dir");
            final JFileChooser jfc = new JFileChooser(cwd);
            final JLabel elapsed = new JLabel("Elapsed time: ");

            JButton filebutton = new JButton("Choose File");
            filebutton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (jfc.showOpenDialog(frame) !=
                    File f = jfc.getSelectedFile();

                    // record the current time and read the file

                    final long s_time = System.currentTimeMillis();
                    readin(f.toString(), textpane);

                    // wait for read to complete and update time

                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            long t = System.currentTimeMillis() -
                            elapsed.setText("Elapsed time: " + t);

            JPanel buttonpanel = new JPanel();

            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            panel.add("North", buttonpanel);
            panel.add("Center", pane);


The program displays a Choose File button. Click on the button,
and a file chooser dialog appears. You can then select a text
file to read into the text area. Depending on which of these two
lines is uncommented:

    final JTextComponent textpane = new JTextArea();
    //final JTextComponent textpane = new JTextPane();

the text will be read into a JTextArea or into a JTextPane.
JTextArea supports plain text (similar to the old AWT TextArea
class), while JTextPane handles text with attributes (such as
underlining or italics).

The program records the time just before reading the file.
Then it records the time after the file is read. The elapsed time
is the difference between the two times. Notice how
SwingUtilities.invokeLater is used to display the elapsed time.
It is necessary because the read method is asynchronous, that is,
the read operation is not complete when the method returns. Display
updating may noticeably lag behind, because updating is done via
events placed on the event queue, and the program calls read from
the event dispatch thread.

  You can demonstrate the display lag by compiling and
  running the program after commenting out a number of

  //    SwingUtilities.invokeLater(new Runnable() {
  //        public void run() {
              long t = System.currentTimeMillis() -
              elapsed.setText("Elapsed time: " + t);
  //         }
  //   });

  You will see that the wrong elapsed time is posted when you
  make this change. The time is calculated after read returns.
  Unfortunately, this calculation fails to account for the fact
  that the file is still being processed for display purposes.  
  The larger the file, the more inaccurate the elapsed time
  calculation. This problem is most pronounced when you read
  into a JTextPane.
Getting back to the example program... so, there will be update
events to process after actionPerformed returns. To deal with this
issue, for timing purposes, SwingUtilities.invokeLater is called
to queue a runnable task. The runnable task displays the elapsed
time once the read/display operation is complete. The task runs
after all the events ahead of it in the queue have been processed.

When you run the test you will see that text can be read into a
JTextArea 3-4 times faster than into a JTextPane. To make sure
that the comparison is fair, you need to ensure that the file
you are reading is either cached or uncached in both cases, that is,
that both file reads are directly from disk, or else directly from
the operating system cache.

The "bottom line" is that JTextPane does more for you than JTextArea,
but at higher cost. If you're simply interested in reading plain
text, there may be no point in paying that cost.

.  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .

best of luck....



Author Comment

ID: 10896296
Thanks Alot.
LVL 92

Expert Comment

ID: 10896322
Sorry didn't realise efficiency was an issue, you didn't seem to have much text to load.
Just thought you want to get your existing code working.

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question