Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 4 123 ... LastLast
Results 1 to 25 of 80

Thread: Multiple instances of a class

  1. #1
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Multiple instances of a class

    Greetings! New to this forum, first time posting. =)

    I'm currently trying to make a log-in or check-in system, it's meant to be able to allow users to log in, log out, and for there to be logs of the date and time the users did this. Issue being that I have never made anything like it before so it's a nice little project where I try to learn as much as possible as I go along.

    Now the current issue that I am having is that I'm terrible with all forms of coding which involves sending data from one class to the other, and that is exactly the problem I am having right now. I have a mainframe.java class which contains all of the GUI, basic JFrame with a couple of JButtons, some text and the like.

    When I press the button "Add Member" currently a JOptionPane.showInputDialog shows up, and I can type in the name of the user. However, this is where I really don't know how to proceed, I have a Member.java class I want to use for keeping track of all of the separate members/users, but I do not know how to send over the data, store it properly, and then call for the respective user whenever I need to refer to it (for example when he/she logs out).

    This is the code for when a button is pushed, and it checks that Add Member is the right one:

    public void actionPerformed(ActionEvent e) 
    	{
     
    	int i = 0;
    	int i2 = 1;
    	boolean cancel = false;
     
    		if(e.getSource() == AMB)
    		{
    			while(cancel == false)
    			{
    				if(members[i] == "")
    				{
    					i2 = i+1;
    					//***This is where I want to send the information to the members class to be stored for overall usage of the new user.
     
    					//Members.class name = new class(arguments); = JOptionPane.showInputDialog(null, "Adding member:");	This is a failure of an attempt of me trying to at the very least send over the name...
    					if(members[i] == null)
    					{
    						members[i] = "";  //In case no name is written, this makes sure that the array slot stays empty for reuse
    					}
     
    					cancel = true;
    				}

    (I skipped the rest because my post was denied when trying to post too much code, so I only posted the most essential bit and if there is anything else in the code that you would like me to post for further clarification feel free to ask.)


    And this is the Members.java class:

    package LoginSystem;
     
    public class Members {
     
    	String name;
    	int lastLoggedIn;
     
    	public Members (String Name, int logIn)
    	{
    		lastLoggedIn = logIn;
    		name = Name;
    	}
    }


    Very basic so far since I don't really know how to flesh it out.

    I'm sorry that I can't post much of what I've tried, but that's mostly because I have no idea of what to try or where to find information of what I could try. I have tried to search around for answers but to no success. =/

    Any help, be it tips, pointers or just general advice in how to proceed would be greatly appreciated!
    Kind regards, Lora.


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Multiple instances of a class

    What is the members array? An array of Strings?
    Are you able to use a List object (such as an ArrayList) and instead store Members object? This way you won't need to worry about keeping slots open, since the List will automatically adjust its size for your needs, and you can store the objects themselves instead of Strings representing members.
    Word of warning here:
    if(members[i] == "")
    You want to compare String values with the String.equals(String) method, not ==:
    if(members[i].equals(""))
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Lora_91 (October 16th, 2013)

  4. #3
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    Yes, the members array is currently a String array, more of a relic from before my friend told me to use a members.java class to keep track of all of the users.

    I'm not familiar with list objects, but it does sound like a much better solution.

    I get an error on this attempt to create it, but I'm guessing it's meant to be something like this?
    private List<Object> object = new ArrayList<Object>();

  5. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Multiple instances of a class

    Yes. But you can change it to accept only your Members objects by saying this:
    private List<Members> object = new ArrayList<Members>();
    The thingy between the < and > is called a Type Parameter. Basically, it restricts the content of your list object to only contain a certain type of Object (including all subclasses of that object). So while List<Object> would accept any Object, List<Members> will only accept Members objects which you create.

    What does the error say? Is an import error or something?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  6. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Lora_91 (October 16th, 2013)

  7. #5
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    private List<Members> object = new ArrayList<Members>();
    Error:
    The type List is not generic; it cannot be parameterized with arguments<Members>
    ArrayList cannot be resolved to a type

  8. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Multiple instances of a class

    Ok, you have not imported the List and ArrayList object. Keep in mind that there are actually two List object in the java SDK. One is a GUI object (it is in the awt package or something, you don't want that one), the other is the data object which you are actually wanting.
    The List and ArrayList objects can be found in the java.util package.
    So add this to the top of your class:
    import java.util.List;
    import java.util.ArrayList;
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  9. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Lora_91 (October 16th, 2013)

  10. #7
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    Done, now the error message is gone, thanks! =)

    How would I go about using it though? I would assume it's something like: Members.class. or something?

    Sorry, really terrible when it comes to connecting classes with each other. =/

  11. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Multiple instances of a class

    To create a new Member and add it to your members list, you would do something like this:
    String nameValue = "someName";
    int loginValue = 0;
    Members member = new Members(nameValue,loginValue); // We are creating a new Members object with the constructor you created, and storing it in the member variable
    object.add(member); // We are adding the new Members object to your List
    I would suggest changing the name of your List<Members> to something other than object. Something which has more meaning, like: membersList or something.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  12. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Lora_91 (October 16th, 2013)

  13. #9
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    Alright, thanks a lot! =)

    Now how would you retrieve information from the list? For example if I want to add all the users to a visible list in the GUI and display whether or not they are online? Also if I were to wish to remove a user, how do I refer to the correct one if I have say, 5 users added and want to remove user 3?

  14. #10
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Multiple instances of a class

    Ok, well, let's say we have a user list which looks like this:
    Index 0: Member("user1",0);
    Index 1: Member("user2",1);
    Index 2: Member("user3",0);

    Now, if we wanted to get a user based on their username, we could add a method like this:
    public Members getMember(String username) {
    	/* This is a shorthand for-loop without a counter. 
    	 * It is the same as:
    	 * for(int i=0;i<membersList.size();i++) {
    	 * 	Members member = membersList.get(i);
    	 *	...
    	 * }
    	 */
    	for(Members member : membersList) {
    		if(username.equals(member.name))
    			return member;
    	}
    	return null;
    }

    If you wanted to remove a member, I would highly recommend removing them based on the member objects, not on the indexes in the List. The reason being is that unless you have extremely strict indexing, you might accidently remove the wrong member. List does have a List.remove(int index) method, but I try to avoid it. To remove a member based on its username, we can add the following method (assuming you already have the first method):
    public void removeMember(String username) {
    	membersList.remove(getMember(username));
    }

    You could then call things like this:
    Members member = getMember("user1");
    removeMember("user2");
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  15. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Lora_91 (October 16th, 2013)

  16. #11
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    Ah, awesome! Thanks a lot! =)

    I learned more from you in a couple of hours than I did trying to teach myself for weeks. ^^


    Should I continue to use the while loop and check the String array members[i] to see if it's empty when I'm looking for the next open spot, or is there a way to add on to the first available?

  17. #12
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    Alright, so I've been working a bit further with the code in attempt to expand it, so far it's going fairly well. An issue I'm having at the moment however is that I need to be able to refer to a user by their index number. Currently we added a way to refer to a user by their name, but my program doesn't always know which name is who, at least not without knowing their index?

    I tried doing the following:

        public Members getIndex(int userIndex)
        {
            for(Members index : membersList)
            {
                if(userIndex == index) // Error message: Incompatible operand types int and Members
                {
                    return index;
                }
                return null;
            }
        }

    As well as adding further on to the Members class to support it:

    public class Members {
     
        String name;
        int lastLoggedIn;
        int index;
        boolean Online;
     
        public Members (String Name, int logIn, int Index, boolean online)
        {
            lastLoggedIn = logIn;
            name = Name;
            Online = online;
            index = Index;
        }
     
     
    }


    Here is where I'm creating the users, this is within the auctionlistener when the add user button is pressed:
            if(e.getSource() == AddMemberButton)
            {
                while(cancel == false)
                {
                    if(members[i].equals(""))
                    {
     
                        String nameValue = JOptionPane.showInputDialog(null, "Adding user:");
     
     
                        if(nameValue == null)
                        {
                            members[i] = "";
                            JOptionPane.showMessageDialog(null, "No username was submitted; sequence aborted.");
     
                        }else
                        {
                            MA++; //MA is currently a Member Amount integer which starts at 0 and increases for every added member
                                      //I wasn't sure if you could do it any other way
                            int loginValue = 0;
                            Members member = new Members(nameValue, loginValue, MA, false); //Creating a new Members object with the constructor we created, and storing it in the member variable
                            membersList.add(member); //Adding the new members object to our list
     
                            UserLoginButton[i] = new JButton("In");
                            UserLoginButton[i].setLocation(0,MA * 30 + 5);
                            UserLoginButton[i].setSize(60,20);
                            UserLoginButton[i].addActionListener(this);
                            memberPanel.add(UserLoginButton[i]);
     
                            UserLogoutButton[i] = new JButton("Out");
                            UserLogoutButton[i].setLocation(0,MA * 30 + 5);
                            UserLogoutButton[i].setSize(60,20);
                            UserLogoutButton[i].addActionListener(this);
     
     
     
     
                            StringMembers[i] = new JLabel(nameValue);
                            StringMembers[i].setLocation(70, MA * 30);
                            StringMembers[i].setSize(60,30);
                            memberPanel.add(StringMembers[i]);
                        }
     
                        cancel = true;
                    }//Closing if
     
                    i++;

    As you can see I'm also creating two buttons for every user, a log in button and a log out button. Only the log in button is visible at first, and the idea being that when logging in the log in button will be replaced with the log out button. This is however not happening, I can create several users and all of them appear as they should with their own respective button, but only the last one reacts to being pressed even though all of them should have been added to the action listener, and it doesn't do anything other than display the JOptionpane.showMessageDialog (which is only there to check if the code is actually being run).

            i = 0;
            while(i < MA)
            {
            	if(e.getSource() == UserLoginButton[i])
                {
                	memberPanel.remove(UserLoginButton[i]);
                	memberPanel.add(UserLoginButton[i]);
                	JOptionPane.showMessageDialog(null, "Logging in!!!");
                }else if(e.getSource() == UserLogoutButton[i])
                {
                	memberPanel.remove(UserLogoutButton[i]);
                	memberPanel.add(UserLoginButton[i]);
                	JOptionPane.showMessageDialog(null, "Logging out: ");
                }
            	i++;
            }

  18. #13
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Multiple instances of a class

    Getting a user by index is much easier.
    Simply say: Members member = memberList.get(index); (where index is an int).
    No looping or anything is necessary. There is also no reason to add an index variable in the Members class.

    Um, I think you have to call memberPanel.revalidate(); after you add or remove buttons. JPanels do not automatically redraw the display. Revalidate should force an update of the JPanel.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  19. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Lora_91 (October 17th, 2013)

  20. #14
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Multiple instances of a class

    You might also consider using CardLayout to change the user interface rather than adding and removing components to a single container. It's much simpler, cleaner, and will result in fewer headaches.

    Another option is to leave the compoents there and enable/disable them and/or change their displayed Labels, but I think these kind of changes - especially the latter - are confusing to the user. Even so, adding and removing components seems to be all the rage these days.

  21. #15
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    Quote Originally Posted by aussiemcgr View Post
    Getting a user by index is much easier.
    Simply say: Members member = memberList.get(index); (where index is an int).
    No looping or anything is necessary. There is also no reason to add an index variable in the Members class.

    Um, I think you have to call memberPanel.revalidate(); after you add or remove buttons. JPanels do not automatically redraw the display. Revalidate should force an update of the JPanel.
    I'm a little bit confused as to how to use the Members member line, the "member" is a new variable that we are creating, which is referring to the int variable index which was previously declared somewhere? Or did I misunderstand it? =/

    if(e.getSource() == RemoveMemberButton)
            {
     
                String k = JOptionPane.showInputDialog(null, "Who would you like to remove?");
                Members member = membersList.get(index); //index cannot be resolved to a variable
     
     
                removeMember(k);
                memberPanel.revalidate();
            }


    Also, is a loop needed here or is there a way to refer specifically to the button in the array that was pressed? Because currently it only reacts to the latest added button, so the loop doesn't even seem to want to work properly, or I just messed up the assignment of the buttons to the actionlistener...

            i = 0;
            while(i < MA)
            {
                if(e.getSource() == UserLoginButton[i])
                {
                    memberPanel.remove(UserLoginButton[i]);
                    memberPanel.add(UserLoginButton[i]);
                    JOptionPane.showMessageDialog(null, "Logging in!!!");
                }else if(e.getSource() == UserLogoutButton[i])
                {
                    memberPanel.remove(UserLogoutButton[i]);
                    memberPanel.add(UserLoginButton[i]);
                    JOptionPane.showMessageDialog(null, "Logging out: ");
                }
                i++;
            }

    Quote Originally Posted by GregBrannon View Post
    You might also consider using CardLayout to change the user interface rather than adding and removing components to a single container. It's much simpler, cleaner, and will result in fewer headaches.

    Another option is to leave the compoents there and enable/disable them and/or change their displayed Labels, but I think these kind of changes - especially the latter - are confusing to the user. Even so, adding and removing components seems to be all the rage these days.
    I haven't heard of CardLayout before but I suppose there's no harm in trying it. When it comes to disabling/enabling it, how well would that work with realigning the position of all of the users?

    Say that I have four users created:
    User1
    User2
    User3
    User4

    User 3 now wishes to leave and must be removed from the program, currently that would leave a gap:
    User1
    User2
    null
    User4

    I was thinking of running a loop when that would move everyone past the removed user up one slot, but I'm not sure if disabling/enabling would make that more confusing?

  22. #16
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Multiple instances of a class

    Quote Originally Posted by Lora_91 View Post
    I'm a little bit confused as to how to use the Members member line, the "member" is a new variable that we are creating, which is referring to the int variable index which was previously declared somewhere? Or did I misunderstand it? =/
    "member" is the Members object returned from the memberList.get(int) method. When you add items to a List, they are automatically added to the end of the list, and indexed accordingly. Assuming you never removed any members, the Members object in index 3 (for example) would be the 4th Members object you added to the list (4th instead of 3rd because indexing starts at 0). It is a new variable, but it is just a reference to the Members object in the List, not a new Members object. For example, if you were to change the username of "member", the Members object in the list would also change accordingly (since the variable and the index of the list are referencing the same physical object in memory).
    Also, is a loop needed here or is there a way to refer specifically to the button in the array that was pressed? Because currently it only reacts to the latest added button, so the loop doesn't even seem to want to work properly, or I just messed up the assignment of the buttons to the actionlistener...

            i = 0;
            while(i < MA)
            {
                if(e.getSource() == UserLoginButton[i])
                {
                    memberPanel.remove(UserLoginButton[i]);
                    memberPanel.add(UserLoginButton[i]);
                    JOptionPane.showMessageDialog(null, "Logging in!!!");
                }else if(e.getSource() == UserLogoutButton[i])
                {
                    memberPanel.remove(UserLogoutButton[i]);
                    memberPanel.add(UserLoginButton[i]);
                    JOptionPane.showMessageDialog(null, "Logging out: ");
                }
                i++;
            }
    A loop would be needed. Perhaps you are incorrectly adding the action listener to the buttons. Nothing in that code stands out to me as "wrong".
    I haven't heard of CardLayout before but I suppose there's no harm in trying it. When it comes to disabling/enabling it, how well would that work with realigning the position of all of the users?

    Say that I have four users created:
    User1
    User2
    User3
    User4

    User 3 now wishes to leave and must be removed from the program, currently that would leave a gap:
    User1
    User2
    null
    User4

    I was thinking of running a loop when that would move everyone past the removed user up one slot, but I'm not sure if disabling/enabling would make that more confusing?
    I'm not sure if card layout is 100% what you want. Although I don't have a very good idea of what you want your GUI to look like.
    When you remove a Members object from your memberList, it will not put a null value in its index. All following index will decrement by one, and the List size will shrink by 1.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  23. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Lora_91 (October 17th, 2013)

  24. #17
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    Quote Originally Posted by aussiemcgr View Post
    "member" is the Members object returned from the memberList.get(int) method. When you add items to a List, they are automatically added to the end of the list, and indexed accordingly. Assuming you never removed any members, the Members object in index 3 (for example) would be the 4th Members object you added to the list (4th instead of 3rd because indexing starts at 0). It is a new variable, but it is just a reference to the Members object in the List, not a new Members object. For example, if you were to change the username of "member", the Members object in the list would also change accordingly (since the variable and the index of the list are referencing the same physical object in memory).
    Ok, I think I understand it a bit better, but I still don't understand why it's telling me that "index cannot be resolved to a variable" at:

    if(e.getSource() == RemoveMemberButton)
            {
     
                String k = JOptionPane.showInputDialog(null, "Who would you like to remove?");
     
                Members member = membersList.get(index); //Error: index cannot be resolved to a variable
                //memberPanel.remove(UserLoginButton[member]);
     
     
               // removeMember(member);
     
                memberPanel.revalidate();
            }

    Is the method built in with the list or do I create it the same way as:
    public Members getMember(String username)    
    {
            for(Members member : membersList)
            {
                if(username.equals(member.name))
                    return member;
            }
            return null;
        }

    Quote Originally Posted by aussiemcgr View Post
    A loop would be needed. Perhaps you are incorrectly adding the action listener to the buttons. Nothing in that code stands out to me as "wrong".
    Hm, I looked over the code and found the error, the String array members[i] was in the if check, and since I no longer use it, it was always true, which meant that int i would always be 0, which was what the buttons arrays were linked to. I changed it to MA but it would probably be better to refer to it to the size of the list + 1 since that's the size it becomes.

            if(e.getSource() == AddMemberButton)
            {
                while(cancel == false)
                {
                    if(members[i].equals("")) //This is the array members, it would probably be better to refer to the listSize + 1? 
                                                   //The if method might not even be needed if that's the case since null gaps aren't left lying around.
                    {
     
                        String nameValue = JOptionPane.showInputDialog(null, "Adding user:");
     
                        if(nameValue == null || nameValue.equals(""))
                        {
                            members[i] = "";
                            JOptionPane.showMessageDialog(null, "No username was submitted; sequence aborted.");
     
                        }else
                        {
                            MA++;
                            int loginValue = 0;
                            Members member = new Members(nameValue, loginValue, false); //Creating a new Members object with the constructor we created, and storing it in the member variable
                            membersList.add(member); //Adding the new members object to our list                   
     
                            UserLoginButton[MA-1] = new JButton("In");
                            UserLoginButton[MA-1].setLocation(0,MA * 30 + 5);
                            UserLoginButton[MA-1].setSize(60,20);
                            UserLoginButton[MA-1].addActionListener(this);
                            memberPanel.add(UserLoginButton[MA-1]);
     
                            UserLogoutButton[MA-1] = new JButton("Out");
                            UserLogoutButton[MA-1].setLocation(0,MA * 30 + 5);
                            UserLogoutButton[MA-1].setSize(60,20);
                            UserLogoutButton[MA-1].addActionListener(this);
     
     
                            StringMembers[MA-1] = new JLabel(nameValue);
                            StringMembers[MA-1].setLocation(70, MA * 30);
                            StringMembers[MA-1].setSize(60,30);
                            memberPanel.add(StringMembers[MA-1]);
                        }
     
                        cancel = true;
                    }//Closing if
     
                    i++;
                }

    Quote Originally Posted by aussiemcgr View Post
    I'm not sure if card layout is 100% what you want. Although I don't have a very good idea of what you want your GUI to look like.
    When you remove a Members object from your memberList, it will not put a null value in its index. All following index will decrement by one, and the List size will shrink by 1.
    I don't have all the details of what the GUI will look like either yet, it depends on what is and isn't possible and how well I can do it in the end. Currently however it's rather simple, bellow is a big simplification of its current form:

    __________________________________________________ _______________
    |--------------------------------Welcome!-------------------------------|
    | Login:-----------------------------------------------------------------|
    | User button + User 1----------------------Possible log information-------|
    | User button + User 2---------------------------------------------------|
    | User button + User 3---------------------------------------------------|
    |---------------------------------Buttons-------------------------------|
    |_________________________________________________ ______________|

    If the list automatically adjusts itself that makes it so much easier! But also all the more important that all user buttons and other user objects refer to the users index number and not the MA (Member Amount) int variable, so that they readjust as well when the list changes.

  25. #18
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Multiple instances of a class

    Wait, so what is the user buttons, vs the buttons you have at the bottom?

    The method is built in. index needs to be an int, representing the index in the list.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  26. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Lora_91 (October 17th, 2013)

  27. #19
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    Quote Originally Posted by aussiemcgr View Post
    Wait, so what is the user buttons, vs the buttons you have at the bottom?
    The buttons at the bottom are basic interface buttons meant to remove and add users, plus more stuff later on as I get it working like fetching logs of a certain user for the past week and stuff like that.

    The user buttons are the log in and log out buttons that are created when the user is created, and therefor should be removed when said user is removed.

    Quote Originally Posted by aussiemcgr View Post
    The method is built in. index needs to be an int, representing the index in the list.
    This confuses me, aren't we trying to get the index number of the user, or otherwise refer to it?
                int randomInt = 0;
                Members member = membersList.get(randomInt);
    This doesn't give me any error messages but I'm unsure of how it helps. =/

  28. #20
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Multiple instances of a class

    Ok, well, first of all, if you only have either the log in OR the log out button at the screen at any given time, there is no reason to have a different button for both. Instead, simply change the text of the button. For example: By default, have the button with the text "Log In". When the user presses that button and logs in, change the text to "Log Out". And when the user presses it again to log out, change it back to "Log In". Then, in your action listener, find the button for the user, and then determine the action the button should do (either log in or log out) based on the current text of the button.


    My bad, I thought you were trying to get the user by index number. To get the index number by the Members object, you can do two things.
    First, if you already have the Members object, you can call:
    Members members = ...;
    int index = membersList.indexOf(members);
    If you just have the username, you would want to loop through the membersList:
    public int getIndexOfMember(String username) {
        for(int i=0;i<membersList.size();i++) {
            if(membersList.get(i).name.equals(username))
                return i;
        }
    }
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  29. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Lora_91 (October 17th, 2013)

  30. #21
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    Quote Originally Posted by aussiemcgr View Post
    Ok, well, first of all, if you only have either the log in OR the log out button at the screen at any given time, there is no reason to have a different button for both. Instead, simply change the text of the button. For example: By default, have the button with the text "Log In". When the user presses that button and logs in, change the text to "Log Out". And when the user presses it again to log out, change it back to "Log In". Then, in your action listener, find the button for the user, and then determine the action the button should do (either log in or log out) based on the current text of the button.
    Neat, I thought of doing that at first but figured it could be difficult to set up the if method in the actionlistener, but if you can check the current text on it then it should be no problem. =)
    How would it work with images though? I was thinking of having say a green image if you're logged in, and a blue image if you're logged out. If it's problematic I could always try to have that as a separate image on the side of it.


    Quote Originally Posted by aussiemcgr View Post
    My bad, I thought you were trying to get the user by index number. To get the index number by the Members object, you can do two things.
    First, if you already have the Members object, you can call:
    Members members = ...;
    int index = membersList.indexOf(members);
    If you just have the username, you would want to loop through the membersList:
    public int getIndexOfMember(String username) {
        for(int i=0;i<membersList.size();i++) {
            if(membersList.get(i).name.equals(username))
                return i;
        }
    }

    Hm, I'm getting: "this method must return a result of type int" from
    public int getIndexOfMember(String username)


    Added a return (Integer) null; and now I'm not getting any error messages, but a notification of "null pointer access: this expression of type Integer is null but requires auto-unboxing"

        public int getIndexOfMember(String username)
        {
        	for(int i = 0; i < membersList.size(); i++)
        	{
        		if(membersList.get(i).name.equals(username))
        			return i;
        	}
        	return (Integer) null;
        }

  31. #22
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Multiple instances of a class

    Buttons can contain both text and images (icons). If your buttons are just images (no text), you can declare variables for your images as class variables and then use == to determine which icon the button is showing.
    To get texts on buttons, just use the getText() method (to set text, use the setText(String) method). Here is an API for all of JButton's methods: JButton (Java Platform SE 7 )

    With regard to your error. Yep, I forgot the null case. After the for loop, add the statement: return -1;
    The compiler was complaining because I left out the case where none of the members in the membersList match the username. In that event, we want to return -1. We return -1 because that is the standard indicator for an invalid index.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  32. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Lora_91 (October 17th, 2013)

  33. #23
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    Ah, thanks a lot! =)

    I'll see if I can put all of this to good use. Thanks for all the help!

  34. #24
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    Ok so I've run into another fairly small issue, but an issue I'm not sure of how to solve non the less. When adding a new member, I've currently set up another JFrame to show up with several text fields and two buttons. Here you can enter in the first name, last name and desired password for your user account. The buttons are merely "complete" and "cancel". The new frame is created in the class memberFrame.java, and the class MainFrame.java creates a new instance of the Members class which is the "account" we are creating, and is supposed to contain the information that is entered in the second frame.



            if(e.getSource() == AddMemberButton)
            {
                while(cancel == false)
                {
                            MA++;
                            int loginValue = 0;
                            Members muffin;
                            muffin = memberFrame.createAndShowMemberFrameGUI();

    The issue is that currently the mainframe creates a Members instance and calls for information to be added which runs the second frame, so far so good, but the createAndShowMemberGUI needs to return the values before it's done collecting them. I tried adding a loop to wait for it but then it doesn't let the JFrame do its work for as long as it's looping. =/

    	public static Members createAndShowMemberFrameGUI() 
    	{
    		memberFrame MF = new memberFrame(); //Creating the new JFrame
    		MF.frame.setContentPane(MF.createContentPane());
    		MF.frame.setSize(WindowWidth,WindowHeight);
    		MF.frame.setLocationRelativeTo(null);
    		MF.frame.setResizable(false);
    		MF.frame.setVisible(true);
     
    		while(true)
    		{
    			if(done == true)
    			{
    				return newMember; //A value needs to be returned, but the value is not yet fetched since the frame was just about to be opened
    			}
     
    			if(cancel == true)
    			{
    				return null;
    			}
     
    			/*
    			try 
    			{
    				Thread.sleep(1000); 
     
    			} catch (InterruptedException e) 
    			{
    				e.printStackTrace();
    			}
    			*/
    		}
     
     
     
    	}

    I'm a bit confused as how to delay the value from being returned whilst still letting the code continue running the created JFrame. I should also note that without the Thread.sleep, the second frame is never actually loaded, well it is but it doesn't show up. With the sleep it does show up but doesn't allow me to do anything, not even close it.

  35. #25
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Multiple instances of a class

    User interfaces that are children of a main JFrame interface are not typically also JFrames. This is because the modality of JFrames cannot be changed from modeless. However, you can do everything with a JDialog that can be done with a JFrame and more, because the modality of the JDialog can be varied according to your needs. I believe the problem you're describing is because the modality of JFrames cannot be changed, but I can't be sure because I don't really understand your description of the problem. You can learn more about modal versus modeless here.

    If I've swung and completely missed, please provide a better explanation, preferably with a short bit of code that demonstrates the problem.

  36. The Following User Says Thank You to GregBrannon For This Useful Post:

    Lora_91 (October 25th, 2013)

Page 1 of 4 123 ... LastLast

Similar Threads

  1. referencing variables from multiple instances of a class?
    By nickdesigner in forum What's Wrong With My Code?
    Replies: 2
    Last Post: July 23rd, 2013, 08:24 PM
  2. Log location of multiple instances of jboss...
    By rathi in forum Java Servlet
    Replies: 2
    Last Post: January 23rd, 2012, 10:46 PM
  3. Multiple class instances ??? But how ???
    By dumb_terminal in forum Object Oriented Programming
    Replies: 6
    Last Post: December 2nd, 2010, 08:42 AM
  4. Replies: 0
    Last Post: December 1st, 2010, 06:10 AM
  5. Multiple instances of linked list
    By thedolphin13 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: October 11th, 2010, 07:48 PM