Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Filling a Vector Object with Strings using BufferedReader question

Posted on 2003-10-21
4
1,105 Views
Last Modified: 2008-03-10
Hello all.  My program loads a text file and displays it in a JTextArea.  It is supposed to display the file similar to PowerPoint (i.e. slides).  It searches the file, and when it finds a blank line (i.e only a '\n') it is supposed concatenate all of the previous lines since the last blank line and addElement the String into the Vector.  Then the scroll bar should display each Vector item depending on the value position of the scrollbar.  The problem I'm having is in my public Vector fileBuffer(String fileName) throws IOException method.  It is reading the lines  and adding all of the previous Vector items to the current item.  Any suggestions on how to fix this would be great.  Here is a link to my test .txt file: http://www.student.gsu.edu/~eeichler1/trivia.txt    You'll notice if you load this file that as you scroll down a few that it's displaying the vector element but the element is the entire file up to that element.  Confused??  Thanks!   Code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;

class SlideViewFrame extends JFrame
{
      private JMenuBar menuBar;
      private JMenu fileMenu, helpMenu;
      private JMenuItem openMenuItem, closeMenuItem, exitMenuItem, aboutMenuItem;
      private JSeparator separator;
      private JToolBar toolBar;
      private JLabel label;
      private JTextArea textArea;
      private JScrollBar scrollBar;
      private JFileChooser fileChooser;
      private Font font = new Font("Sans Serif", Font.PLAIN, 36);
      private Icon fileIcon = new ImageIcon("open.gif");
      private OpenAction openAction = new OpenAction("Open", fileIcon);
      private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

      //Method that gets the current screen size and reduces the vertical
      //size by 30 pixels
      private static int getScreenHeight()
      {
            double height;
            height = (screenSize.getHeight() - 30);
            return (int)height;
      }
      
      //Method for frame construction
      public SlideViewFrame()
      {
            //Set title and size
            setTitle("SlideView");
            setSize((int)screenSize.getWidth(), getScreenHeight());
            
            //Listener for clicking "About"
            ActionListener aboutListener = new ActionListener()
            {
                  public void actionPerformed(ActionEvent evt)
                  {
                        JOptionPane.showMessageDialog(null,
                        "SlideView\nVersion 1.0\nCopyright 2003 Eric Eichler",
                      "About SlideView", JOptionPane.INFORMATION_MESSAGE);
                  }
            };
            
            //Listener for clicking "Exit"
            ActionListener exitListener = new ActionListener()
            {
                  public void actionPerformed(ActionEvent evt)
                  {
                        System.exit(0);
                  }
            };
            
            //Create menu bar and add items
            menuBar = new JMenuBar();
            setJMenuBar(menuBar);
            
            //Items for the "file" menu
            fileMenu = new JMenu("File");
            fileMenu.setMnemonic(KeyEvent.VK_F);
            menuBar.add(fileMenu);
            
            fileMenu.add(openAction);

            closeMenuItem = new JMenuItem("Close", KeyEvent.VK_C);
            fileMenu.add(closeMenuItem);
            
            separator = new JSeparator();
            fileMenu.add(separator);
            
            exitMenuItem = new JMenuItem("Exit", KeyEvent.VK_X);
            exitMenuItem.addActionListener(exitListener);
            fileMenu.add(exitMenuItem);
            
            //Items for the "help" menu
            helpMenu = new JMenu("Help");
            helpMenu.setMnemonic(KeyEvent.VK_H);
            menuBar.add(helpMenu);

            aboutMenuItem = new JMenuItem("About SlideView", KeyEvent.VK_A);
            aboutMenuItem.addActionListener(aboutListener);
            helpMenu.add(aboutMenuItem);
            
            //Create toolbar
            toolBar = new JToolBar();
            toolBar.setFloatable(false);
            toolBar.add(openAction);
            
            //Create text area and scrollbar
            textArea = new JTextArea();
            textArea.setEditable(false);
            textArea.setFont(font);
            
            //Create scrollbar
            scrollBar = new JScrollBar();
            scrollBar.setVisible(true);
            scrollBar.setEnabled(false);
            
            //Create label
            label = new JLabel("");
            label.setVisible(false);

            //Add components to the container
            Container container = getContentPane();
            container.setLayout(new BorderLayout());
            container.add(toolBar, BorderLayout.NORTH);
            container.add(label, BorderLayout.SOUTH);
            container.add(textArea, BorderLayout.CENTER);
            container.add(scrollBar, BorderLayout.EAST);
      }
      
      //Class that creates the AbstractAction objects for the "Open" functions
      //on the menubar and toolbar.
      class OpenAction extends AbstractAction
       {
            public OpenAction(String text, Icon icon)
            {
                  super(text, icon);
                  putValue(Action.SHORT_DESCRIPTION, "Open");
                  putValue(Action.MNEMONIC_KEY, new Integer(java.awt.event.KeyEvent.VK_O));
                  putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control O"));
            }
            
            //Method that displays the JFileChooser and returns the name of the selected file
            public String fileChooser() throws IOException
            {
                  String fileName, currentPath = new String();
                  
                  File currentDirectory = new File(".");
                  currentPath = currentDirectory.getAbsolutePath();
                  fileChooser = new JFileChooser(currentPath);
                  fileChooser.showOpenDialog(null);
            
                  File selectedFile = fileChooser.getSelectedFile();
                  fileName = selectedFile.getName();
                  
                  return fileName;
            }

            //Method that reads the contents of the selected file and stores it into a Vector Object
            public Vector fileBuffer(String fileName) throws IOException
            {
                  FileReader fileIn = new FileReader(fileName);
                  BufferedReader in = new BufferedReader(fileIn);
                  Vector stringVector = new Vector();
                  String tempString = new String();
                  tempString.equals(null);
                  
                  while(true)
                  {
                        String currentLine = in.readLine();
                        if(currentLine == null)
                        {
                              if(tempString.length() > 0)
                              {
                                    stringVector.addElement(tempString);
                              }
                              break;
                        }
                        else if(currentLine.length() > 0)
                        {
                              tempString = tempString + "  " + currentLine + '\n';                                    
                        }
                        else
                        {
                              stringVector.addElement(tempString);
                              tempString.equals(null);
                        }
                  }
                  return stringVector;
            }
            
            public void scrollBarAction(final Vector vector)
            {
                  AdjustmentListener adjustmentListener = new AdjustmentListener()
                  {
                        public void adjustmentValueChanged(AdjustmentEvent adj_evt)
                        {
                              System.out.println((String)vector.elementAt(scrollBar.getValue()));
                              textArea.setText((String)vector.elementAt(scrollBar.getValue()));
                        }
                  };
                  
                  int size = vector.size();
                  scrollBar.setValues(0, 1, 0, size + 1);
                scrollBar.setEnabled(true);
                scrollBar.addAdjustmentListener(adjustmentListener);
                  label.setText("Slide " + (scrollBar.getValue()+1) + " of " + (scrollBar.getMaximum()-1));
                  label.setHorizontalAlignment(JLabel.CENTER);
                  label.setVisible(true);
            }
            
            public void actionPerformed(ActionEvent evt)
          {
                  try
                  {
                        String name = new String(fileChooser());
                        Vector stringVector = new Vector(fileBuffer(name));
                        scrollBarAction(stringVector);
                        textArea.setText((String)stringVector.elementAt(0));
                  }
                  catch(IOException e)
                  {
                        System.out.println("Error: " + e.getMessage());
                        System.exit(-1);
                  }
            }
      }
}

//Main driver class
public class SlideView
{
      public static void main(String args[])
      {
            JFrame frame = new SlideViewFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            //frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
      }
}
0
Comment
Question by:ike2010
  • 3
4 Comments
 
LVL 9

Expert Comment

by:yongsing
ID: 9596382
What is the following suppose to do?

tempString.equals(null);

This is just a test to see whether tempString is null. Since you are not reading the return value of equals(), this line is meaningless.  If you want to set it to null, you should do

tempString = null;
0
 
LVL 9

Expert Comment

by:yongsing
ID: 9596393
You should also close the stream after reading:

in.close();
0
 
LVL 9

Accepted Solution

by:
yongsing earned 500 total points
ID: 9596433
Try this:

public Vector fileBuffer(String fileName) throws IOException
{
    FileReader fileIn = new FileReader(fileName);
    BufferedReader in = new BufferedReader(fileIn);
    Vector stringVector = new Vector();
    String tempString = "";
             
    while(true)
    {
        String currentLine = in.readLine();
        if(currentLine == null)
        {
            if(tempString.length() > 0)
            {
                stringVector.addElement(tempString);
            }
            break;
        }
        else if(currentLine.length() > 0)
        {
            tempString = tempString + "  " + currentLine + '\n';                              
        }
        else
        {
            stringVector.addElement(tempString);
            tempString = "";
        }
    }
    in.close();
    return stringVector;
}
0
 

Author Comment

by:ike2010
ID: 9596577
besides setting the string to tempString.equals("");  was the main cause of the error not usin in.close();  ?  thanks for the quick response by the way.  i'm a java rookie and really appreciate it.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
hibernate example using maven 12 57
runtime exception 2 41
Is there a simpler dropbox system? 10 34
restrict decimal places for double datatype 10 19
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

856 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