Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / December 2006

Tip: Looking for answers? Try searching our database.

problem passing arraylist between constructors?

Thread view: 
df118 - 27 Dec 2006 02:47 GMT
Hi guys,

I've very new to java, and I think i'm having a little trouble
understanding scope. The program I'm working on is building a jtree
from an xml file, to do this an arraylist (xmlText) is being built and
declared in the function Main. It's then called to an overloaded
constructor which processes the XML into a jtree:

public Editor( String title, ArrayList xmlText ) throws
ParserConfigurationException

Later, in the second constructor which builds my GUI, I try and call
the same arraylist so I can parse this XML into a set of combo boxes,
but get an error thrown up at me that i'm having a hard time solving- :

public Editor( String title  ) throws ParserConfigurationException

// additional code
//  Create a read-only combobox- where I get an error.

   String [] items = (String []) xmlText.toArray (new String[
xmlText.size () ]);

         JComboBox queryBox = new JComboBox(items);
       JComboBox queryBox2 = new JComboBox(items);
       JComboBox queryBox3 = new JComboBox(items);
       JComboBox queryBox4 = new JComboBox(items);
       JComboBox queryBox5 = new JComboBox(items);

This is the way I understand the Arraylist can be converted to a string
to use in the combo boxs. However I get an error thrown up at me here
at about line 206, which as far as I understand is because when the
overloaded constructor calls the other constructor:

public Editor( String title ) throws ParserConfigurationException -

It does not pass in the variable xmlText.

I'm told that the compiler complains because xmlText  is not defined
at that point:

- it is not a global variable or class member

- it has not been passed into the function
and

- it has not been declared inside the current function

Can anyone think of a solution to this problem? As I say a lot of this
stuff is still fairly beyond me, I understand the principles behind the
language and the problem, but the solution has been evading me so far.
If anyone could give me any help or a solution here I'd be very
grateful- I'm getting totally stressed over this.

The code I'm working on is below, I've highlighted where the error
crops up too- it's about line 200-206 area. Sorry for the length, I was
unsure as to how much of the code I should post.

public class Editor extends JFrame implements ActionListener
{
 // This is the XMLTree object which displays the XML in a JTree
 private XMLTree               XMLTree;
 // MODDED. This is the textArea object that will display the raw XML
text, and handle other thingss.
 private JTextArea        textArea, textArea2, textArea3;
 // One JScrollPane is the container for the JTree, the other is for
the textArea
 private JScrollPane         jScroll, jScrollRt, jScrollUp,
jScrollBelow;
 private JSplitPane        splitPane, splitPane2;

 private JPanel    panel;
// This JButton handles the tree Refresh feature
 private JButton            refreshButton;
 // This Listener allows the frame's close button to work properly
 private WindowListener      winClosing;
    private JSplitPane splitpane3;

// Menu Objects
  private          JMenuBar                menuBar;
  private          JMenu                fileMenu;
  private          JMenuItem            newItem, openItem, saveItem,
exitItem;

// This JDialog object will be used to allow the user to cancel an exit
command
  private JDialog        verifyDialog;

// These JLabel objects will be used to display the error messages
  private JLabel            question;

// These JButtons are used with the verifyDialog object
  private JButton        okButton, cancelButton;

  private JComboBox            testBox;

 // These two constants set the width and height of the frame
 private static final int FRAME_WIDTH = 600;
 private static final int FRAME_HEIGHT = 450;

 /**
  * This constructor passes the graphical construction off to the
overloaded constructor
  * and then handles the processing of the XML text
  */
 public Editor( String title, ArrayList xmlText ) throws
ParserConfigurationException
 {

     this( title );

    textArea.setText( ( String )xmlText.get( 0 ) + "\n" );
     for ( int i = 1; i < xmlText.size(); i++ )
           textArea.append( ( String )xmlText.get( i ) + "\n" );
    try
    {
        XMLTree.refresh( textArea.getText() );
    }
    catch( Exception ex )
    {
        String message = ex.getMessage();
        System.out.println( message );
    }//end try/catch
 } //end Editor( String title, String xml )

 /**
  * This constructor builds a frame containing a JSplitPane, which in
turn contains two
JScrollPanes.
  * One of the panes contains an XMLTree object and the other contains
a JTextArea object.
  */
 public Editor( String title  ) throws ParserConfigurationException
 {
     // This builds the JFrame portion of the object

     super( title );

     Toolkit            toolkit;
     Dimension            dim, minimumSize;
     int                screenHeight, screenWidth;

     // Initialize basic layout properties
     setBackground( Color.lightGray );
     getContentPane().setLayout( new BorderLayout() );

     // Set the frame's display to be WIDTH x HEIGHT in the middle of
the screen
     toolkit = Toolkit.getDefaultToolkit();
     dim = toolkit.getScreenSize();
     screenHeight = dim.height;
     screenWidth = dim.width;
     setBounds( (screenWidth-FRAME_WIDTH)/2,
(screenHeight-FRAME_HEIGHT)/2, FRAME_WIDTH,
FRAME_HEIGHT );

     // Build the Menu
    fileMenu = new JMenu( "File" );
    newItem = new JMenuItem( "New" );
    newItem.addActionListener( new newMenuHandler() );
    openItem = new JMenuItem( "Open" );
    openItem.addActionListener( new openMenuHandler() );
    saveItem = new JMenuItem( "Save" );
    saveItem.addActionListener( new saveMenuHandler() );
    exitItem = new JMenuItem( "Exit" );
    exitItem.addActionListener( new exitMenuHandler() );
    fileMenu.add( newItem );
    fileMenu.add( openItem );
    fileMenu.add( saveItem );
    fileMenu.add( exitItem );

    menuBar = new JMenuBar();
    menuBar.add( fileMenu );
    setJMenuBar( menuBar );

    // Build the verify dialog
    verifyDialog = new JDialog( this, "Confirm Exit", true );
    verifyDialog.setBounds( (screenWidth-200)/2, (screenHeight-100)/2,
200, 100 );

    question = new JLabel( "Are you sure you want to exit?" );

    okButton = new JButton( "OK" );
    okButton.addActionListener( this );

    cancelButton = new JButton( "Cancel" );
    cancelButton.addActionListener( this );

    verifyDialog.getContentPane().setLayout( new FlowLayout() );
    verifyDialog.getContentPane().add( question );
    verifyDialog.getContentPane().add( okButton );
    verifyDialog.getContentPane().add( cancelButton );
    verifyDialog.hide();

     // Set the Default Close Operation
    setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE );

    // Create the refresh button object
    refreshButton = new JButton( "Refresh" );
    refreshButton.setBorder( BorderFactory.createRaisedBevelBorder() );
    refreshButton.addActionListener( this );

    // Add the button to the frame
    getContentPane().add( refreshButton, BorderLayout.NORTH );

     // Create two JScrollPane objects
     jScroll = new JScrollPane();
    jScrollRt = new JScrollPane();

    // First, create the JTextArea:
     // Create the JTextArea and add it to the right hand JScroll
     textArea = new JTextArea( 200,150 );
     jScrollRt.getViewport().add( textArea );

     // Next, create the XMLTree
     XMLTree = new XMLTree();
     XMLTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION
);
     XMLTree.setShowsRootHandles( true );

     // A more advanced version of this tool would allow the JTree to
be editable
     XMLTree.setEditable( false );

     // Wrap the JTree in a JScroll so that we can scroll it in the
JSplitPane.
     jScroll.getViewport().add( XMLTree );

      // Create the JSplitPane and add the two JScroll objects
     splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, jScroll,
jScrollRt );
     splitPane.setOneTouchExpandable(true);
     splitPane.setDividerLocation(200);

       jScrollUp = new JScrollPane();

       jScrollBelow=new JScrollPane();

// Here is were the error is coming up

   String [] items = (String []) xmlText.toArray (new String[
xmlText.size () ]);

         JComboBox queryBox = new JComboBox(items);
       JComboBox queryBox2 = new JComboBox(items);
       JComboBox queryBox3 = new JComboBox(items);
       JComboBox queryBox4 = new JComboBox(items);
       JComboBox queryBox5 = new JComboBox(items);

     * I'm adding the scroll pane to the split pane,
       * a panel to the top of the split pane, and some uneditible
combo boxes
       *  to them. Then I'll rearrange them to rearrange them, but
unfortunately am getting an error thrown up above.

       */
       panel = new JPanel();
       panel.add(queryBox);
       panel.add(queryBox2);
       panel.add(queryBox3);
       panel.add(queryBox4);
       panel.add(queryBox5);

       jScrollUp.getViewport().add( panel );

       // Now building a text area

       textArea3 = new JTextArea(200, 150);
       jScrollBelow.getViewport().add( textArea3 );

       splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
jScrollUp, jScrollBelow);
       splitPane2.setPreferredSize( new Dimension(300, 200) );
       splitPane2.setDividerLocation(100);
       splitPane2.setOneTouchExpandable(true);

   // in here can change the contents of the split pane
       getContentPane().add(splitPane2,BorderLayout.SOUTH);

     // Provide minimum sizes for the two components in the split pane
     minimumSize = new Dimension(200, 150);
     jScroll.setMinimumSize( minimumSize );
     jScrollRt.setMinimumSize( minimumSize );

     // Provide a preferred size for the split pane
     splitPane.setPreferredSize( new Dimension(400, 300) );

     // Add the split pane to the frame
     getContentPane().add( splitPane, BorderLayout.CENTER );

     //Put the final touches to the JFrame object
     validate();
     setVisible(true);

     // Add a WindowListener so that we can close the window
     winClosing = new WindowAdapter()
     {
        public void windowClosing(WindowEvent e)
        {
           verifyDialog.show();
        }
     };
     addWindowListener(winClosing);
 } //end Editor()

 /**
  * When a user event occurs, this method is called.  If the action
performed was a click
  * of the "Refresh" button, then the XMLTree object is updated using
the current XML text
  * contained in the JTextArea
  */
 public void actionPerformed( ActionEvent ae )
 {
    if ( ae.getActionCommand().equals( "Refresh" ) )
    {
        try
        {
            XMLTree.refresh( textArea.getText() );
        }
        catch( Exception ex )
        {
            String message = ex.getMessage();
            ex.printStackTrace();
        }//end try/catch
    }
    else if ( ae.getActionCommand().equals( "OK" ) )
    {
        exit();
    }
    else if ( ae.getActionCommand().equals( "Cancel" ) )
    {
        verifyDialog.hide();
    }//end if/else if
 } //end actionPerformed()

// Program execution begins here.  An XML file (*.xml) must be passed
into the method
 public static void main( String[] args )
 {
     String                    fileName = "";
     BufferedReader            reader;
     String                    line;
     ArrayList                 xmlText = null;
     Editor                 Editor;

     // Build a Document object based on the specified XML file
     try
     {
       if( args.length > 0 )
         {
           fileName = args[0];

           if ( fileName.substring( fileName.indexOf( '.' ) ).equals(
".xml" ) )
           {
             reader = new BufferedReader( new FileReader( fileName )
);
             xmlText = new ArrayList();

             while ( ( line = reader.readLine() ) != null )
             {
            xmlText.add( line );
             } //end while ( ( line = reader.readLine() ) != null )

             // The file will have to be re-read when the Document
object is parsed
             reader.close();

             // Construct the GUI components and pass a reference to
the XML root node
             Editor = new Editor( "Editor 1.0", xmlText );
           }
           else
           {
             help();
           } //end if ( fileName.substring( fileName.indexOf( '.' )
).equals( ".xml" ) )
       }
       else
       {
            Editor = new Editor( "Editor 1.0" );
       } //end if( args.length > 0 )
     }
     catch( FileNotFoundException fnfEx )
     {
        System.out.println( fileName + " was not found." );
        exit();
     }
     catch( Exception ex )
     {
        ex.printStackTrace();
        exit();
     }// end try/catch
  }// end main()

  // A common source of operating instructions
  private static void help()
  {
     System.out.println( "\nUsage: java Editor filename.xml" );
     System.exit(0);
  } //end help()

  // A common point of exit
  public static void exit()
  {
     System.out.println( "\nThank you for using Editor 1.0" );
     System.exit(0);
  } //end exit()

  class newMenuHandler implements ActionListener
  {
    public void actionPerformed( ActionEvent ae )
    {
        textArea.setText( "" );

        try
        {
            // Next, create a new XMLTree
             XMLTree = new XMLTree();
             XMLTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION );
             XMLTree.setShowsRootHandles( true );

             // A more advanced version of this tool would allow the JTree
to be editable
             XMLTree.setEditable( false );
        }
        catch( Exception ex )
        {
            String message = ex.getMessage();
            ex.printStackTrace();
        }//end try/catch
    }//end actionPerformed()
  }//end class newMenuHandler

/* The standard java.io classes were used to create the open file
implementation.
  A lazier solution would be to use the JtextArea's ability to read
directly from
  a file.  The saveMenuHandler() implements a lazy save solution.
Either way is fine.
*/
  class openMenuHandler implements ActionListener
  {
    JFileChooser        jfc;
    Container            parent;
    int                choice;

    openMenuHandler()
    {
        super();
        jfc = new JFileChooser();
        jfc.setSize( 400,300 );
        jfc.setFileFilter( new XmlFileFilter() );

        parent = openItem.getParent();
    }//end openMenuHandler()

    public void actionPerformed( ActionEvent ae )
    {
        // Displays the jfc and sets the dialog to 'open'
        choice = jfc.showOpenDialog( parent );

        if ( choice == JFileChooser.APPROVE_OPTION )
        {
            String            fileName, line;
            BufferedReader        reader;

            fileName = jfc.getSelectedFile().getAbsolutePath();

            try
            {
                reader = new BufferedReader( new FileReader( fileName ) );

                textArea.setText( reader.readLine() + "\n" );

                    while ( ( line = reader.readLine() ) != null )
                    {
                    textArea.append( line + "\n" );
                    } //end while ( ( line = reader.readLine() ) != null )

                    // The file will have to be re-read when the Document
object is parsed
                    reader.close();

                XMLTree.refresh( textArea.getText() );
            }
            catch ( Exception ex )
            {
                String message = ex.getMessage();
                ex.printStackTrace();
            }//end try/catch

            jfc.setCurrentDirectory( new File( fileName ) );
        } //end if ( choice == JFileChooser.APPROVE_OPTION )

    }//end actionPerformed()
  }//end class openMenuHandler

  class saveMenuHandler implements ActionListener
  {
    JFileChooser        jfc;
    Container            parent;
    int                choice;

    saveMenuHandler()
    {
        super();
        jfc = new JFileChooser();
        jfc.setSize( 400,300 );
        jfc.setFileFilter( new XmlFileFilter() );

        parent = saveItem.getParent();
    }//end saveMenuHandler()

    public void actionPerformed( ActionEvent ae )
    {
        // Displays the jfc and sets the dialog to 'save'
        choice = jfc.showSaveDialog( parent );

        if ( choice == JFileChooser.APPROVE_OPTION )
        {
            String            fileName;
            File                fObj;
            FileWriter            writer;

            fileName = jfc.getSelectedFile().getAbsolutePath();

            try
            {
                writer = new FileWriter( fileName );

                textArea.write( writer );

                    // The file will have to be re-read when the Document
object is parsed
                    writer.close();
            }
            catch ( IOException ioe )
            {
                ioe.printStackTrace();
            }//end try/catch

            jfc.setCurrentDirectory( new File( fileName ) );
        } //end if ( choice == JFileChooser.APPROVE_OPTION )

    }//end actionPerformed()
  }//end class saveMenuHandler

  class exitMenuHandler implements ActionListener
  {
    public void actionPerformed( ActionEvent ae )
    {
        verifyDialog.show();
    }//end actionPerformed()
  }//end class exitMenuHandler

  class XmlFileFilter extends javax.swing.filechooser.FileFilter
  {
    public boolean accept( File fobj )
    {
        if ( fobj.isDirectory() )
            return true;
        else
            return fobj.getName().endsWith( ".xml" );
    }//end accept()

    public String getDescription()
    {
        return "*.xml";
    }//end getDescription()
  }//end class XmlFileFilter

   } //end class Editor

Sorry if this post has been a bit lengthy, any help you guys could give
me solving this would be really appreciated.

Thanks,

Iain.
Andrew Thompson - 27 Dec 2006 06:35 GMT
..
> ...crops up too- it's about line 200-206 area. Sorry for the length, I was
> unsure as to how much of the code I should post.

Generally, an SSCCE is considered a good way to
express a code problem.  For more details on the
SSCCE, see http://www.physci.org/codes/sscce
..
> Sorry ...

No need for apologies, but...

>...if this post has been a bit lengthy,

..likewise do not expect many* people to look through that
amount of code snippets and descriptions (*I predict '0').

>...any help you guys could give
> me solving this would be really appreciated.

Please see the SSCCE document, for lots of tips
on making that code example, as well as further
disscussion as to why not many will read the first
post.

Andrew T.
Oliver Wong - 27 Dec 2006 20:25 GMT
> However I get an error thrown up at me here
> at about line 206, which as far as I understand is because when the
> overloaded constructor calls the other constructor:

   Can you post the error message?

   - Oliver
df118 - 28 Dec 2006 03:55 GMT
Hi Oliver,

The error I was receiving was

'cannot find symbol error, variable XMLtext,
location ClassEditor'

I've tried to resolve this issue by merging both constructors into one,
the-

'public Editor( String title, ArrayList xmlText ) throws
ParserConfigurationException'

constructor, but in doing so I'm now getting an error here,

      }
      else
       {
            Editor = new Editor( "Editor 1.0" );
       } //end if( args.length > 0 )

in the main method, which I haven't altered, specifically in  the
'    Editor = new Editor( "Editor 1.0" );'

line, at line 341, saying

Cannot find symbol
Symbol constructor editor (java.lang.string)
Location class editor.

So now I'm completely confused, heh.

Andrew- thanks for your tips, I'm new to newsgroups so I'll try to
keep to the proper  etiquette from now on in.

> > However I get an error thrown up at me here
> > at about line 206, which as far as I understand is because when the
[quoted text clipped - 3 lines]
>
>     - Oliver
Andrew Thompson - 28 Dec 2006 04:33 GMT
...
> Andrew- thanks for your tips,

You are welcome.  But ..

>..I'm new to newsgroups ..

(You have found a good group, to start with.)

>...so I'll try to
> keep to the proper  etiquette ...

..the advice I gave you on the SSCCE is sure not
'netiquette', so much as 'a good way to investigate/solve
a problem', or.. failing that, produce 'a self contained
example' that shows the same problems you see.

Whereas 'etiquette' or 'netiqette' might be,
"please refrain from top-posting, in future".

>...from now on in.

And I think you will find more people care about
'top-posting' than ever cared about an SSCCE.  ;-)

Andrew T.
Oliver Wong - 28 Dec 2006 15:21 GMT
> I've tried to resolve this issue by merging both constructors into one,
> the-
[quoted text clipped - 20 lines]
>
> So now I'm completely confused, heh.

   Try to copy and paste the error message exactly, rather than
paraphrasing it. For example, I bet the error doesn't say

"Symbol constructor editor (java.lang.string)"

but rather:

"Symbol constructor Editor (java.lang.String)

   The difference between uppercase and lowercase is important.

   Anyway, assuming I've made the correct guess as to what the real error
message is, it's saying that there's no constructor for Editor which takes a
single String as a parameter. Looking at the declaration you gave, public
Editor( String title, ArrayList xmlText ), it looks like the constructor is
expecting two parameters, one of which is a String, and the other is an
ArrayList.

   - Oliver


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.