Page 1 of 2 12 LastLast
Results 1 to 20 of 30
  1. #1
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default Print to file from GUI using second class

    Ok, I am doing an assignment for an intermediate java class and have been instructed to build a program where user inputs city, state, and population (multiple times if desired) and then print the info to the file. We were instructed to use a second class (CityRecord) for getters and setters. I have decided to go with a GUI for data entry, and push a button to enter the data, push a different button to print to file. I am having an issue pulling the information from the jFrame to the CityRecord class, and having an issue printing to file. Can anyone look at my code and give me some pointers please?

    jPanel form (PopulationForm.java):
    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /*
     * PopulationForm.java
     *
     * Created on Feb 14, 2011, 12:28:57 PM
     */
    
    package phase4dbpopulation;
    
    import java.io.*;
    /**
     *
     * @author Jon and Jessica
     */
    public class PopulationForm extends javax.swing.JFrame {
    
        /** Creates new form PopulationForm */
        public PopulationForm() {
            initComponents();
        }
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
        private void initComponents() {
    
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            city = new javax.swing.JTextField();
            state = new javax.swing.JTextField();
            population = new javax.swing.JTextField();
            jLabel3 = new javax.swing.JLabel();
            jLabel4 = new javax.swing.JLabel();
            jLabel5 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jButton3 = new javax.swing.JButton();
            jButton4 = new javax.swing.JButton();
    
            jLabel1.setText("jLabel1");
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jLabel2.setText("Population Form");
    
            jLabel3.setText("City:");
    
            jLabel4.setText("State:");
    
            jLabel5.setText("Population");
    
            jButton1.setText("Clear Form");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jButton2.setText("QUIT");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });
    
            jButton3.setText("Print to File");
            jButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton3ActionPerformed(evt);
                }
            });
    
            jButton4.setText("Enter Data");
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(52, 52, 52)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4)
                        .addComponent(jLabel5))
                    .addGap(29, 29, 29)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(city, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)
                        .addComponent(state)
                        .addComponent(population))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 157, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addComponent(jButton3))
                    .addGap(58, 58, 58))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(227, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addGap(212, 212, 212))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(162, Short.MAX_VALUE)
                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(139, 139, 139))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel2)
                    .addGap(38, 38, 38)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(city, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)
                        .addComponent(jButton1))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(state, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)
                        .addComponent(jButton2))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(population, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5)
                        .addComponent(jButton3))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
                    .addComponent(jButton4)
                    .addContainerGap())
            );
    
            pack();
        }// </editor-fold>//GEN-END:initComponents
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
            // When Clear Button is pressed, clear all text fields
            city.setText("");
            state.setText("");
            population.setText("");
    
        }//GEN-LAST:event_jButton1ActionPerformed
    
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
            // When EXIT Button is pressed, exit application
            System.exit(0);
        }//GEN-LAST:event_jButton2ActionPerformed
    
        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
            // When PRINT TO FILE Button is pressed, print all entered data to file population.txt
            FileOutputStream out; // declare a file output object
            PrintStream p; // declare a print stream object
    
            try
                    {
                            // Create a new file output stream
                            // connected to "population.txt"
                            out = new FileOutputStream("population.txt");
    
                            // Connect print stream to the output stream
                            p = new PrintStream( out );
    
                            p.println (CityRecord.java);
    
                            p.close();
                    }
                    catch (Exception e)
                    {
                            System.err.println ("Error writing to file");
                    }
    
    
        }//GEN-LAST:event_jButton3ActionPerformed
    
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new PopulationForm().setVisible(true);
                }
            });
    
        }
    
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JTextField city;
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JButton jButton4;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JLabel jLabel5;
        private javax.swing.JTextField population;
        private javax.swing.JTextField state;
        // End of variables declaration//GEN-END:variables
    
    }
    CityRecord.java:
    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package Phase4DBPopulation;
    
    /**
     *
     * @author Jon and Jessica
     */
    // Fig. 17.5: CityRecord.java
    // CityRecord class maintains information for one account.
     // packaged for reuse
    
    public class CityRecord
    {
    
       private String city;
       private String state;
       private double population;
    
       // no-argument constructor calls other constructor with default values
       public CityRecord()
       {
          this(  "", "", 0.0 ); // call three-argument constructor
       } // end no-argument CityRecord constructor
    
       // initialize a record
       public CityRecord( String city, String state, double population )
       {
          setCity(  city );
          setState(  state );
          setPopulation( population );
       } // end three-argument CityRecord constructor
    
      
    
       // set city name
       public void setCity( String cityName )
       {
          cityName = city;
       } // end method setCity
    
       // get city name
       public String getCity()
       {
    
           return city;
       } // end method getCity
    
       // set state name
       public void setState( String stateName )
       {
          stateName = state;
       } // end method setState
    
       // get state name
       public String getState()
       {
          
           return state;
       } // end method getState
    
       // set population
       public void setPopulation( double pop )
       {
          pop = population;
       } // end method setPopulation
    
       // get Population
       public double getPopulation()
       {
          return population;
       } // end method getPopulation
    } // end class CityRecord
    
    /*************************************************************************
    * (C) Copyright 1992-2010 by Deitel & Associates, Inc. and               *
    * Pearson Education, Inc. All Rights Reserved.                           *
    *                                                                        *
    * DISCLAIMER: The authors and publisher of this book have used their     *
    * best efforts in preparing the book. These efforts include the          *
    * development, research, and testing of the theories and programs        *
    * to determine their effectiveness. The authors and publisher make       *
    * no warranty of any kind, expressed or implied, with regard to these    *
    * programs or to the documentation contained in these books. The authors *
    * and publisher shall not be liable in any event for incidental or       *
    * consequential damages in connection with, or arising out of, the       *
    * furnishing, performance, or use of these programs.                     *
    *************************************************************************/
    I know that the print button is complete and currently just creates my file and prints a line of text. I am trying to get the CityRecord to pull the text out of the text field right now. Any suggestions would be much appreciated.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    What's not working? Are you getting error messages? Have you done some debugging such as using println statements, and the results? What specifically is the problem? The more you can tell us, the better we can help.

    And as an important aside, should you be posting copyrighted code without permission?
    Last edited by Fubarable; 02-17-2011 at 05:52 PM.

  3. #3
    Debugger is offline Member
    Join Date
    Jan 2011
    Posts
    27
    Rep Power
    0

    Default

    Suggestion without looking at code because im in class, but when in the GUI and they hit the save button, get the information from the GUI with

    Variable name = JTextArea.getText();

    then once you have all the information create the object of CityRecord, passing it the variables the user entered. Then write that object to the file, or write a printInfo method and print that to the file

  4. #4
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    What's not working? Are you getting error messages? Have you done some debugging such as using println statements, and the results? What specifically is the problem? The more you can tell us, the better we can help.

    And as an important aside, should you be posting copyrighted code without permission?
    As for the debugging, haven't made it that far. I am using netBeans and when there is an issue with the code it shows a red line under the mistake, and I know that the code isn't right. Right now I am just trying to get the text from the text field into the CityRecord class.

    As for the copyrighted code, I have implicit instructions from the instructor to re-use the code, but I pretty much changed every aspect of the copyrighted code and simply forgot to remove the message. I just used deital's framework as a design tool and then made my own code based on theirs.

  5. #5
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    Ok, I will try that. I will set the enter data button to contain the text in the text field upon the button press, and then pass the variable to the CityRecord class.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by iamjonsmith View Post
    As for the debugging, haven't made it that far. I am using netBeans and when there is an issue with the code it shows a red line under the mistake, and I know that the code isn't right. Right now I am just trying to get the text from the text field into the CityRecord class.
    A red line/error where? What is the actual error message? It's kind of important for you to tell us any and all important details for us to be able to help you.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Edit: oh, I see:

    Java Code:
    p.println(CityRecord.java);

    This doesn't make sense as it appears you're trying to write the code from the CityRecord.java file into another file? Perhaps instead you mean to create a new CityRecord object with the data in the JTextFields?

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    And then once you get the data, how do you plan to write it to a file? As Strings to a text file or as objects that are serialized into a binary file? If strings, I'm not sure that you even need to create CityRecord objects out of the text field data.

  9. #9
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    Ok, first problem. I HAVE to use the CityRecord to pull the information from my jtextfields per instructor. This is where the first problem is happening. I think I am trying to call the variable wrong. Here is what I came up with and didn't work. Starting with just getting the city name:

    In PopulationForm when the user pressed the Enter Data button text fields should pass the text to a variable as follows:

    Java Code:
     private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
            String cityName;
            String stateName;
            String populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = population.getText();
        }
    I then try to pass the variable containing the text from the text fields to the CityRecord class but am failing miserably as follows:

    Java Code:
     // set city name
       public void setCity( String cityName )
       {
          cityName = PopulationForm.cityName;  //**error here**
       } // end method setCity
    
       // get city name
       public String getCity()
       {
           
           return city;
       } // end method getCity
    here is the errror I get:

    C:\Users\Jon and Jessica\Documents\Class Work\Java Programming\Phase 4\DB\Phase4DBPopulation\src\Phase4DBPopulation\Cit yRecord.java:42: cannot find symbol
    symbol : variable PopulationForm
    location: class Phase4DBPopulation.CityRecord
    cityName = PopulationForm.cityName;

    I know the println method wrong. I stopped working on it for a bit because I found out I found the issue with the variables.

  10. #10
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    BTW I have also tried doing pretty much the same thing in the getCity method and it failed the same way: code was as follows:
    Java Code:
     // set city name
       public void setCity( String cityName )
       {
          cityName = city;
       } // end method setCity
    
       // get city name
       public String getCity()
       {
           city = PopulationForm.cityName;
           return city;
       } // end method getCity
    error message as follows:

    C:\Users\Jon and Jessica\Documents\Class Work\Java Programming\Phase 4\DB\Phase4DBPopulation\src\Phase4DBPopulation\Cit yRecord.java:48: cannot find symbol
    symbol : variable PopulationForm
    location: class Phase4DBPopulation.CityRecord
    city = PopulationForm.cityName;

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by iamjonsmith View Post
    Ok, first problem. I HAVE to use the CityRecord to pull the information from my jtextfields per instructor. This is where the first problem is happening. I think I am trying to call the variable wrong. Here is what I came up with and didn't work. Starting with just getting the city name:

    In PopulationForm when the user pressed the Enter Data button text fields should pass the text to a variable as follows:

    Java Code:
     private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
            String cityName;
            String stateName;
            String populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = population.getText();
        }
    I then try to pass the variable containing the text from the text fields to the CityRecord class but am failing miserably as follows:

    Java Code:
     // set city name
       public void setCity( String cityName )
       {
          cityName = PopulationForm.cityName;  //**error here**
       } // end method setCity
    
       // get city name
       public String getCity()
       {
           
           return city;
       } // end method getCity
    Don't change CityRecord in such a way. CityRecord should set it's cityName based on the parameter passed in and that's it. The way you had it in the first post is correct and should not be changed. Think of it this way, you shouldn't tie CityRecord to the GUI in any way, since CityRecord should be able to be used by any class that wants to use it, and CityRecord should have to have no knowledge about the class that wants to use it. So again, leave it alone.

    Instead if you must create a CityRecord object, then do it in the PopulationForm class, in the actionPerformed method where you gather the data. Create your CityRecord instance there:

    Java Code:
     private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
            String cityName;
            String stateName;
            String populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = population.getText();
    
            // *****
            //  create your CityRecord object here with the data obtained above.  ****
        }
    You may wish to post your actual assignment specifications.

  12. #12
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    Ok, instructions for assignment:

    Develop an application that reads city, state and population entered from the user and writes this information to a file. The application should continuously prompt for this population information until terminated by the user.

    Example file:
    Jamestown FL 50000
    Domville CO 10000
    Jennyboro FL 30000
    Blountsville CO 5000

    The choice of using command line vs. GUI was left to us, and since I am trying to learn this for Real World Application, I figured most clients would expect a GUI if I was designing this for them, so that is what I am trying to learn. The only additional instruction from our professor was that if we chose to use a GUI, we would have to modify the AccountRecord class from our text book, make it a CityRecord class and use it to pull the text out of the jtextfields, and then pass them to the print method of our choice.

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    OK, what I recommend is this:

    • Give your GUI an ArrayList<CityRecord> variable, say call it cityRecordList.
    • In the actionPerformed method associated with your Enter Data JButton, extract the data from the fields, use the data to create a CityRecord object and add this object to the cityRecordList via its add(....) method.
    • In the actionPerformed method associated with your Print to File JButton, go loop through the cityRecordList using a for loop, and print each record into your file. Inside the loop you'll need to call the getter methods of CityRecord on each object in the ArrayList, and use this to print the info to the file, and at the bottom of the for loop you'll want to print a new line to the file, such as can be done by calling println() on your PrintStream object.
    • Rename your components with smart variable names. For instance jButton1 should instead be clearFormButton, jButton2 should be called clearButton, etc... NetBeans will allow you to do this easily by right clicking on the JButtons (and any and all other components) and changing their names. This will make it much easier for you and us to debug your code.
    Last edited by Fubarable; 02-17-2011 at 07:35 PM.

  14. #14
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Don't change CityRecord in such a way. CityRecord should set it's cityName based on the parameter passed in and that's it. The way you had it in the first post is correct and should not be changed. Think of it this way, you shouldn't tie CityRecord to the GUI in any way, since CityRecord should be able to be used by any class that wants to use it, and CityRecord should have to have no knowledge about the class that wants to use it. So again, leave it alone.

    Instead if you must create a CityRecord object, then do it in the PopulationForm class, in the actionPerformed method where you gather the data. Create your CityRecord instance there:

    You may wish to post your actual assignment specifications.
    Ok, I switched the CityRecord back to the original.

    As for the object, do you mean in the actionPerformed do something like:

    Java Code:
     private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            String cityName;
            String stateName;
            String populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = population.getText();
    
           CityRecord CityRecord = new CityRecord("","","");
        }
    when I do this I get an error:

    C:\Users\Jon and Jessica\Documents\Class Work\Java Programming\Phase 4\DB\Phase4DBPopulation\src\Phase4DBPopulation\Pop ulationForm.java:193: cannot find symbol
    symbol : class CityRecord
    location: class phase4dbpopulation.PopulationForm
    CityRecord CityRecord = new CityRecord("","","");
    C:\Users\Jon and Jessica\Documents\Class Work\Java Programming\Phase 4\DB\Phase4DBPopulation\src\Phase4DBPopulation\Pop ulationForm.java:193: cannot find symbol
    symbol : class CityRecord
    location: class phase4dbpopulation.PopulationForm
    CityRecord CityRecord = new CityRecord("","","");

    Sorry, I am just going in circles it seems. I don't know, but I am just not grasping the concept. I feel like an idiot. I am really sorry dude. Your help is much appreciated

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by iamjonsmith View Post
    Ok, I switched the CityRecord back to the original.

    Good.


    As for the object, do you mean in the actionPerformed do something like:

    Java Code:
     private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            String cityName;
            String stateName;
            String populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = population.getText();
    
           CityRecord CityRecord = new CityRecord("","","");
        }
    when I do this I get an error:

    C:\Users\Jon and Jessica\Documents\Class Work\Java Programming\Phase 4\DB\Phase4DBPopulation\src\Phase4DBPopulation\Pop ulationForm.java:193: cannot find symbol
    symbol : class CityRecord
    location: class phase4dbpopulation.PopulationForm
    CityRecord CityRecord = new CityRecord("","","");
    C:\Users\Jon and Jessica\Documents\Class Work\Java Programming\Phase 4\DB\Phase4DBPopulation\src\Phase4DBPopulation\Pop ulationForm.java:193: cannot find symbol
    symbol : class CityRecord
    location: class phase4dbpopulation.PopulationForm
    CityRecord CityRecord = new CityRecord("","","");

    Sorry, I am just going in circles it seems. I don't know, but I am just not grasping the concept. I feel like an idiot. I am really sorry dude. Your help is much appreciated

    No, you're getting closer, step by step.

    OK first off this line:

    Java Code:
           CityRecord CityRecord = new CityRecord("","","");
    For one, you don't want to give a variable the same exact name as the class. Make the variable's first letter lower-case.
    Next, you'll want to place the Strings obtained into the CityRecord constructor rather than simply passing blank Strings "".
    Finally , the third and last parameter to the CityRecord constructor isn't a String but a double, and you'll need to convert the data in the JTextField's text from String to double using Double.parseDouble(...)

    I think that the GUI is not finding the CityRecord class because it is in a different package (again capitalization matters), and you might want to either place both java files in the same package or import the CityRecord class into the GUI class.
    Last edited by Fubarable; 02-17-2011 at 08:00 PM.

  16. #16
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    New Code with changes to button names, working with ArrayList, and a few other changes suggested:

    Main Class:

    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /*
     * PopulationForm.java
     *
     * Created on Feb 14, 2011, 12:28:57 PM
     */
    
    package phase4dbpopulation;
    
    import java.io.*;
    import java.util.ArrayList;
    /**
     *
     * @author Jon and Jessica
     */
    public class PopulationForm extends javax.swing.JFrame {
    
        /** Creates new form PopulationForm */
        public PopulationForm() {
            initComponents();
        }
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            city = new javax.swing.JTextField();
            state = new javax.swing.JTextField();
            population = new javax.swing.JTextField();
            jLabel3 = new javax.swing.JLabel();
            jLabel4 = new javax.swing.JLabel();
            jLabel5 = new javax.swing.JLabel();
            clearFormButton = new javax.swing.JButton();
            quitButton = new javax.swing.JButton();
            printToFileButton = new javax.swing.JButton();
            enterDataButton = new javax.swing.JButton();
    
            jLabel1.setText("jLabel1");
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jLabel2.setText("Population Form");
    
            jLabel3.setText("City:");
    
            jLabel4.setText("State:");
    
            jLabel5.setText("Population");
    
            clearFormButton.setText("Clear Form");
            clearFormButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    clearFormButtonActionPerformed(evt);
                }
            });
    
            quitButton.setText("QUIT");
            quitButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    quitButtonActionPerformed(evt);
                }
            });
    
            printToFileButton.setText("Print to File");
            printToFileButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    printToFileButtonActionPerformed(evt);
                }
            });
    
            enterDataButton.setText("Enter Data");
            enterDataButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    enterDataButtonActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(52, 52, 52)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4)
                        .addComponent(jLabel5))
                    .addGap(29, 29, 29)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(city, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)
                        .addComponent(state)
                        .addComponent(population))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 157, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(clearFormButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(quitButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addComponent(printToFileButton))
                    .addGap(58, 58, 58))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(233, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addGap(212, 212, 212))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(168, Short.MAX_VALUE)
                    .addComponent(enterDataButton, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(139, 139, 139))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jLabel2)
                    .addGap(38, 38, 38)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(city, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)
                        .addComponent(clearFormButton))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(state, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)
                        .addComponent(quitButton))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(population, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5)
                        .addComponent(printToFileButton))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
                    .addComponent(enterDataButton)
                    .addContainerGap())
            );
    
            pack();
        }// </editor-fold>
    
        private void clearFormButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // When Clear Button is pressed, clear all text fields
            city.setText("");
            state.setText("");
            population.setText("");
    
        }                                        
    
        private void quitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // When EXIT Button is pressed, exit application
            System.exit(0);
        }                                        
    
        private void printToFileButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // When PRINT TO FILE Button is pressed, print all entered data to file population.txt
            FileOutputStream out; // declare a file output object
            PrintStream p; // declare a print stream object
    
            try
                    {
                            // Create a new file output stream
                            // connected to "population.txt"
                            out = new FileOutputStream("population.txt");
    
                            // Connect print stream to the output stream
                            p = new PrintStream( out );
    
                            p.println ("CityRecord will Print Here");
    
                            p.close();
                    }
                    catch (Exception e)
                    {
                            System.err.println ("Error writing to file");
                    }
    
    
        }                                        
    
        private void enterDataButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            ArrayList<cityRecord> cityRecordList = (CityRecord.cityRecord());
            String cityName;
            String stateName;
            double populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = Double.parseDouble(population.getText());
    
           cityRecord CityRecord = new CityRecord("City","State",0.0);
           cityRecordList.add(CityRecord);
        }                                        
    
        /**
        * @param args the command line arguments
        */
    
    
        public static void main(String args[]) {
                java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new PopulationForm().setVisible(true);
                }
            });
    
        }
    
        // Variables declaration - do not modify
        private javax.swing.JTextField city;
        private javax.swing.JButton clearFormButton;
        private javax.swing.JButton enterDataButton;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JLabel jLabel5;
        private javax.swing.JTextField population;
        private javax.swing.JButton printToFileButton;
        private javax.swing.JButton quitButton;
        private javax.swing.JTextField state;
        // End of variables declaration
    
    }
    Also, I didn't realize the two classes were in different packages, I will correct that and see if it helps resolve some issues.

    I am trying to figure out the ArrayList Suggestion, and this is what I have so far:

    Java Code:
    private void enterDataButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            ArrayList<cityRecord> cityRecordList = (CityRecord.cityRecord());
            String cityName;
            String stateName;
            double populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = Double.parseDouble(population.getText());
    
           cityRecord CityRecord = new CityRecord("City","State",0.0);
           cityRecordList.add(CityRecord);
        }
    I know it is not quite right, but I am still working on it. I also corrected the capitalization issue and both classes should be included in the same package.
    Last edited by iamjonsmith; 02-17-2011 at 08:13 PM.

  17. #17
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    No, your code creates a new ArrayList inside of that method each time the button is pressed, and as soon as the method is complete, the ArrayList, being a local variable, will disappear. Instead the ArrayList must be declared in the class, not in any method of the class, so that it will be visible throughout the class, and it needs to be constructed either at declaration or in the class's constructor, so it is created only once and not recreated each time a button is pressed. Then you add to the ArrayList in the method above. Then later the other button can use the same ArrayList (because it was declared in the class), and extract data in a for loop to print the data it contains.

  18. #18
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    Do you mean like this:

    Java Code:
      private void enterDataButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            
            String cityName;
            String stateName;
            double populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = Double.parseDouble(population.getText());
    
           
        }                                        
        
      // ArrayList built outside of method, but inside class
        ArrayList cityRecordList = new ArrayList();
        cityRecordList.add(CityRecord.CityRecord());  //**error here
        /**
        * @param args the command line arguments
        */
    error as follows:
    C:\Users\Jon and Jessica\Documents\Class Work\Java Programming\Phase 4\DB\Phase4DBPopulation\src\Phase4DBPopulation\Pop ulationForm.java:200: <identifier> expected
    cityRecordList.add(CityRecord.CityRecord());

    It still doesn't seem to be finding the CityRecord class for some reason.

  19. #19
    iamjonsmith is offline Member
    Join Date
    Feb 2011
    Posts
    16
    Rep Power
    0

    Default

    Ok, I figured out part of it. I created the ArrayList outside of the method as the above code showed, but then I moved the cityRecordList.add(e) into the Enter Data button code as follows:

    Java Code:
     private void enterDataButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
            
            String cityName;
            String stateName;
            double populationNum;
            cityName = city.getText();
            stateName = state.getText();
            populationNum = Double.parseDouble(population.getText());
    
            cityRecordList.add(cityName);
            cityRecordList.add(stateName);
            cityRecordList.add(populationNum);
        }
    Is this starting to look a little better? I will still need to pull the data from the form to the CityRecord class, and then from CityRecord into the array to make my professor happy. I would like to get rid of the CityRecord class, it would be easier, but gotta do what I gotta do I guess. I at least think I am getting it together and heading in the right direction.

  20. #20
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Almost. The ArrayList should be generic (if this is allowed):

    Java Code:
    ArrayList<CityRecord> cityRecordList = new ArrayList<CityRecord>();
    Regardless, you don't want to add cityName, stateName and populationNum individually to the ArrayList. Please re-read my recommendations above carefully on what should be added:

    extract the data from the fields, use the data to create a CityRecord object and add this object to the cityRecordList via its add(....) method.

Page 1 of 2 12 LastLast

Similar Threads

  1. Print info from a different class?
    By liquidtoon in forum New To Java
    Replies: 3
    Last Post: 11-01-2010, 01:19 PM
  2. Print Array as String through class file?
    By ocarabal in forum New To Java
    Replies: 3
    Last Post: 06-08-2010, 05:22 AM
  3. Print Variable From One Class to Output on another.
    By Lyricid in forum New To Java
    Replies: 8
    Last Post: 02-27-2010, 01:56 PM
  4. Replies: 3
    Last Post: 03-19-2009, 05:00 PM
  5. Print the text file and print preview them
    By Java Tip in forum java.awt
    Replies: 0
    Last Post: 06-22-2008, 11:04 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •