简体   繁体   English

Java的,我的arrayLists遇到麻烦

[英]java, having trouble with my arrayLists

I am working on a program for my Java II class. 我正在为Java II类编写程序。 It is a simple contacts application. 这是一个简单的联系人应用程序。 You enter a name and a number and click an addJButton. 您输入一个名称和一个数字,然后单击一个addJButton。 This takes the information and stores it into an arrayList. 这将获取信息并将其存储到arrayList中。 There is a JPanel that has a back and next JButton that cycles through the added contacts. 有一个JPanel,具有一个后退JButton和一个下一个JButton,可循环显示添加的联系人。 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

Your problem is not with ArrayList per se. 您的问题不是ArrayList本身。 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! 当您尝试创建第二个联系人时,您还将遇到问题,因为您仅创建了一个联系人,因此将继续覆盖您的数组,您将拥有一个arrayList,该数组引用了同一对象! :S :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. 您应该阅读有关Java对象的更多信息,它是整个语言的基础,并且您需要先清楚地理解它,然后才能继续。

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. “ this”关键字对于告诉Java您仅指“ this”对象的范围非常重要。 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, eg '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'. 如果您不使用'this'并且没有类变量,那么Java将会越过该类的更大范围,并且会发现给定变量只有一个实例,例如'name',而使用就像一个'this'前缀,因此您可能会认为不需要使用'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. 请参见Java类中的静态成员。

Edit 2: 编辑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'. 这不是很清楚,我举了一个例子来帮助阐明静态类的成员,但是请看这篇文章,以更好地理解您应该并且需要使用“ 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());

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM