Staver
Staver

Reputation: 63

java, having trouble with my arrayLists

I am working on a program for my Java II class. It is a simple contacts application. You enter a name and a number and click an addJButton. This takes the information and stores it into an arrayList. There is a JPanel that has a back and next JButton that cycles through the added contacts. I am really awful with array/arraylists right now(trying to get better). Could someone tell me why my code is not working? Thanks in advance!

package blackbook;

/**
*
* 
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.text.DecimalFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

public class BlackBook extends JFrame
{

// JLabel and JTextField for name
private JLabel nameEnteredJLabel;
private JTextField nameEnteredJTextField;

// JLabel and JTextField for number
private JLabel numberEnteredJLabel;
private JTextField numberEnteredJTextField;

//JButton for add contact
private JButton addContactJButton;

//JPanel for contacts
private JPanel contactsJPanel;

//JLabel and JTextField for nameStored
private JLabel nameStoredJLabel;
private JTextField nameStoredJTextField;

//JLabel and JTextField for number stored
private JLabel numberStoredJLabel;
private JTextField numberStoredJTextField;

//JButton and JLabel for back
private JButton backJButton;
private JLabel backJLabel;

//JButon and JLabel for next
private JButton nextJButton;
private JLabel nextJLabel;

// contact object contains data for newly entered contacts
private Contact newContact;

// ArrayList contains contacts entered by user
private ArrayList contactArrayList = new ArrayList();

private int contactID = 0; // ID for new contacts

// position used to track location when the user is
// browsing through the list of contacts
private int position = 0;

//no-argument constructor
public BlackBook()
{
    createUserInterface();

}

// create and position GUI components; register event handlers
public void createUserInterface()
{
    // get content pane for attaching GUI components
    Container contentPane = getContentPane();

    // enable explicit positioning of GUI components
    contentPane.setLayout(null);

    // set up nameEnteredJLabel
    nameEnteredJLabel = new JLabel();
    nameEnteredJLabel.setBounds(50, 50, 50, 50);
    nameEnteredJLabel.setText ( "Name: ");
    contentPane.add( nameEnteredJLabel );

    // set up nameEnteredJTextField
    nameEnteredJTextField = new JTextField();
    nameEnteredJTextField.setBounds(50, 90, 100, 30);
    nameEnteredJTextField.setHorizontalAlignment(JTextField.CENTER);
    nameEnteredJTextField.setEditable( true );
    contentPane.add (nameEnteredJTextField);

    // set up numberEnteredJLabel
    numberEnteredJLabel = new JLabel();
    numberEnteredJLabel.setBounds (50, 130, 100, 30);
    numberEnteredJLabel.setText ( "Phone Number:" );
    contentPane.add (numberEnteredJLabel);

    // set up numberEnteredJTextField
    numberEnteredJTextField = new JTextField();
    numberEnteredJTextField.setBounds(50, 170, 100, 30);
    numberEnteredJTextField.setHorizontalAlignment(JTextField.CENTER);
    numberEnteredJTextField.setEditable (true);
    contentPane.add (numberEnteredJTextField);

    // set up addJButton
    addContactJButton = new JButton();
    addContactJButton.setBounds( 50, 230, 140, 30);
    addContactJButton.setText( "Add Contact" );
    contentPane.add( addContactJButton );
    //set up addJButton action listener
    addContactJButton.addActionListener(

       new ActionListener() // anonymous inner class
       {
           // event handler called when addJButton is pressed
           public void actionPerformed( ActionEvent event )
           {
               addContactJButtonActionPerformed( event );
           }        

       }    // end anonymous inner class  

    ); // end call to addActionListener

    // set up contactsJPanel
    contactsJPanel = new JPanel( new BorderLayout() );
    contactsJPanel.setBounds (250, 75, 200, 350);
    contactsJPanel.setLayout ( null );
    contactsJPanel.setBackground(Color.gray);
    contactsJPanel.setBorder(
        new TitledBorder( "Contacts" ) );
    contentPane.add ( contactsJPanel );

    // set up nameStoredJLabel
    nameStoredJLabel = new JLabel();
    nameStoredJLabel.setBounds( 25, 30, 100, 30);
    nameStoredJLabel.setText ( "Name:" );
    nameStoredJLabel.setLayout ( null );
    contactsJPanel.add( nameStoredJLabel );


    // set up nameStoredJTextField
    nameStoredJTextField = new JTextField();
    nameStoredJTextField.setBounds ( 20, 55, 100, 30);
    nameStoredJTextField.setHorizontalAlignment 
                         ( nameStoredJTextField.CENTER);
    nameStoredJTextField.setEditable (false);
    contactsJPanel.add ( nameStoredJTextField );

    // set up numberStoredJLabel
    numberStoredJLabel = new JLabel();
    numberStoredJLabel.setBounds ( 20, 95, 100, 30);
    numberStoredJLabel.setText (" Phone Number:" );
    numberStoredJLabel.setLayout ( null );
    contactsJPanel.add ( numberStoredJLabel );

    // set up numberStoredJTextField
    numberStoredJTextField = new JTextField();
    numberStoredJTextField.setBounds ( 20, 120, 100, 30 );
    numberStoredJTextField.setHorizontalAlignment 
                           ( numberStoredJTextField.CENTER); 
    numberStoredJTextField.setEditable ( false );
    contactsJPanel.add ( numberStoredJTextField );

    // set up backJLabel
    //backJLabel = new JLabel();
    //backJLabel.setBounds ( 120, 25, 30, 35 );
    //backJLabel.setText ( "Back" );
    //backJLabel.setLayout ( null );
    //contactsJPanel.add ( backJLabel );

    // set up backJButton
    backJButton = new JButton();
    backJButton.setBounds ( 20, 200, 90, 30);
    backJButton.setText ( "Back" );
    contactsJPanel.add ( backJButton );
    //set up action listener
    backJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            public void actionPerformed ( ActionEvent event )
            { 
                backJButtonActionPerformed ( event );
            }       

        } // end anonymous inner class

    ); // end call to addActionListener

    // set up nextJLabel
    //nextJLabel = new JLabel();
    //nextJLabel.setBounds ( 100, 43, 43, 43 );
    //nextJLabel.setLayout ( null );
    //contentPane.add ( contactsJPanel );

    // set up nextJButton
    nextJButton = new JButton();
    nextJButton.setBounds ( 100, 200, 90, 30 );
    nextJButton.setText ( "Next" );
    contactsJPanel.add ( nextJButton );
    //set up action listener
    nextJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            public void actionPerformed ( ActionEvent event )
            {
                nextJButtonActionPerformed ( event );
            }
        } // end anonymous inner class

    ); // end call to addActionListener

    // set properties of application's window
    setTitle ( "Black Book" ); // set title bar text
    setSize ( 500, 500 );      // set window size
    setVisible ( true );       // display window

} // end method createUserInterface        

private void addContactJButtonActionPerformed( ActionEvent event )
{   

    setContactData(); // update information

    // add new contact to contactArrayList
    contactArrayList.add( newContact );
    position = contactArrayList.size() - 1;

 // end method addContacJButtonActionPerformed

}        

// move to previous contact
private void backJButtonActionPerformed ( ActionEvent event )
{
   if ( position > 0 )
   {
       position--; // move position back by 1
   }    
   else // go to last element in list
   {
       position = contactArrayList.size() - 1;
   }    

   // set and load contact
   loadContact();

}    // end mathod backJButtonActionPerformed

// move to next contact
private void nextJButtonActionPerformed ( ActionEvent event )
{
    if ( position < contactArrayList.size() - 1)
    {
        position++; // move position forward by 1
    }    
    else
    {
        position = 0; // go to first element in list
    }   

    // load information of contact
    loadContact();

}   // end method nextJButtonActionPerformed 

// set all information about the Contact
private void setContactData()
{
    newContact.setName( nameEnteredJTextField.getText());
    newContact.setNumber( numberEnteredJTextField.getText());

} // end method setContactData

// display all information about the Contact
private void loadContact()
{
    // retrieve contact from list
    newContact = ( Contact ) contactArrayList.get( position );

    // display contact data
    nameEnteredJTextField.setText(newContact.getName());
    numberEnteredJTextField.setText(newContact.getNumber());

} // end method loadContact     

//clear all information about the contact
private void clearComponents()
{
    nameEnteredJTextField.setText ( " " );
    numberEnteredJTextField.setText ( " " );

} // end method clearComponents     

// enable/disable JButtons
private void setJButtons ( boolean state )
{
    backJButton.setEnabled ( state );
    nextJButton.setEnabled ( state );

    // disable navigation if not multiple packages
    if ( contactArrayList.size() < 2 )
    {
        nextJButton.setEnabled(false);
        backJButton.setEnabled(false);
    }    

}    




/**
 * @param args the command line arguments
 */
public static void main(String[] args) 
{    
    BlackBook application = new BlackBook();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
}    // end method main 


}

secondary file

package blackbook;

/**
*
* 
*/
public class Contact 
{
// member data
private String name;
private String number;


// set the contact properties
private void setContact ( String nameValue, String numberValue)
{
    name = nameValue;
    number = numberValue;
}        

// get the name
public String getName()
{
    return name;
}       

// set the name
public void setName ( String nameValue)
{
    name = nameValue;
}        

// get the number
public String getNumber()
{
    return number;
}        

// set the number
public void setNumber( String numberValue )
{
    number = numberValue;
}



} // end class contact

Upvotes: 0

Views: 61

Answers (1)

Richard Dunn
Richard Dunn

Reputation: 6780

Your problem is not with ArrayList per se. It seems to be with how you are creating Contact objects. In this case you are only declaring a contact:

private Contact newContact;

but not instantiating it:

private Contact newContact = new Contact();

You're also going to run into problems when you try to create a second contact, because you've only created one, you're going to keep overwriting it in your array, you'll have an arrayList of references to the same object! :S

Instead of declaring/instantiating it at the start, you're better off just creating a new one every time the button is clicked:

private void addContactJButtonActionPerformed( ActionEvent event )
{   
    Contact newContact = new Contact();

    contactArrayList.add( newContact );

    position = contactArrayList.size() - 1;

}

Also, the best way to create these is with a constructor, and not just setters and getters. Notice how it has the same name as the class, is public, and has no modifiers; that's a constructor.

public class Contact 
{
// member data
private String name;
private String number;


// constructor
public Contact (String nameValue, String numberValue)
{
    this.name = nameValue;
    this.number = numberValue;
} 

It's then called like:

Contact someContact = new Contact(nameEnteredJTextField.getText(), numberEnteredJTextField.getText());

I think after that you're on your way a bit better. You should read more about Objects in Java, it's fundamental to the entire language and you need to understand it clearly before you can progress.

Edit:

No, it's not a dumb question. Every time you create a new object, you're running that bit of code for that object, and that object is unique. There are situations, however, where you can create a class of objects that share some class variables. The 'this' keyword is very important in telling Java that you're only referring to the scope of 'this' object. If you don't use a 'this' and there are no class variables, Java will look past the larger scope of the class and see that there's only one instance of the given variable, e.g. 'name' and just use is like there was a 'this' prefix, so you may be forgiven for thinking that there's no need for using a 'this'. But when you write more complicated code, there very much will be a need for specifying the scope of the variable, so it's better to get into the habit now.

See Static Members in Java classes.

Edit 2:

That wasn't very clear, I made an example to help clarify the static class members, but see this post to better understand all the reasons you should, and need to, use 'this'.

Employee Class:

public class Employee {

    // instance
    private String firstName;
    private String lastName;
    private int empID;

    // global
    private static int empIDinc = 0;

    // constructor
    public Employee(String first, String last){

        // local to this instance
        this.firstName = first;
        this.lastName = last;

        // global across all employees
        empIDinc ++;
        empID = empIDinc;
        }

    public String toString() {
        // added employee ID to string
        return firstName + ' ' + lastName + " ID: " + Integer.toString(empID);
    }
}

Test class. Run it to see the difference.

public class test {

    public static void main(String[] args){

        Employee e1 = new Employee("Richard", "Dunn");
        Employee e2 = new Employee("Richard", "Dunn");
        Employee e3 = new Employee("Richard", "Dunn");


        System.out.println(e1.toString());
        System.out.println(e2.toString());
        System.out.println(e3.toString());

    }
}

Upvotes: 1

Related Questions