java,我的arrayLists有问题

时间:2015-10-10 21:32:38

标签: java arraylist

我正在为我的Java II课程开发一个程序。这是一个简单的联系人应用程序输入名称和数字,然后单击addJButton。这将获取信息并将其存储到arrayList中。有一个JPanel有一个后面和下一个JButton循环添加的联系人。我现在对阵列/ arraylists非常糟糕(试图变得更好)。有人能告诉我为什么我的代码无效吗?提前谢谢!

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 


}

辅助文件

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

1 个答案:

答案 0 :(得分:1)

你的问题不在于ArrayList本身。它似乎与你如何创建Contact对象有关。在这种情况下,您只是声明一个联系人:

private Contact newContact;

但没有实例化它:

private Contact newContact = new Contact();

当您尝试创建第二个联系人时,您也会遇到问题,因为您只创建了一个联系人,您将继续覆盖您的阵列, ; ll有一个对同一对象的引用的数组列表! :S

不是在开始时声明/实例化它,而是每次点击按钮时创建一个新的更好:

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

    contactArrayList.add( newContact );

    position = contactArrayList.size() - 1;

}

此外,创建这些的最好方法是使用构造函数,而不仅仅是setter和getter。注意它与类的名称是一样的,是公共的,没有修饰符;那是一个构造函数。

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


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

然后它被称为:

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

我想在那之后你会更好一点。您应该阅读有关Java中的对象的更多信息,它是整个语言的基础,您需要在进展之前清楚地理解它。

编辑:

不,这不是一个愚蠢的问题。每次创建新对象时,都要为该对象运行该位代码,并且该对象是唯一的。但是,在某些情况下,您可以创建一组共享某些类变量的对象。这个&#39;这个&#39;关键字对于告诉Java你只是指这个&#39;这个&#39;的范围非常重要。宾语。如果你不使用这个&#39;并且没有类变量,Java将超越类的较大范围,并且看到只有给定变量的一个实例,例如&#39;名称&#39;只是使用就像有一个&#39;这个&#39;前缀,所以你可能会认为没有必要使用这个&#39;。但是当你编写更复杂的代码时,很需要指定变量的范围,所以现在养成习惯会更好。

请参阅Java类中的静态成员。

编辑2:

这不是很清楚,我做了一个例子来帮助澄清静态班级成员,但请参阅this post以更好地了解您应该,并且需要使用&#39;这个& #39;

员工类:

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);
    }
}

测试课。运行它以查看差异。

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());

    }
}