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 3 of 4 FirstFirst 1234 LastLast
Results 51 to 75 of 80

Thread: Multiple instances of a class

  1. #51
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,660
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Multiple instances of a class

    Ok, we are going to get drastic.
    We need to figure out what is happening. We want to see:
    1. If the dispose method is called
    2. If the dispose method ends
    You could use a debugger if you know how, or we can sort of "hack" it for now.
    I won't go into the details as to why this works, but here is what we want to do:
    Where you create your dialog2 object, change this:
    dialog2 = new JDialog(dialog1, "", Dialog.ModalityType.APPLICATION_MODAL);
    into this:
    dialog2 = new JDialog(dialog1, "", Dialog.ModalityType.APPLICATION_MODAL) {
        @Override
        public void dispose() {
            System.out.println("Entered dispose");
            super.dispose();
            System.out.println("Exiting dispose");
        }
    };

    Then run the program and tell me if those two statements print out to the console.
    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/

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

    Lora_91 (October 25th, 2013)

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

    Default Re: Multiple instances of a class

    It does not, and I get a notification message on the line where we create the dialog2:

            dialog2 = new JDialog(dialog1, "", Dialog.ModalityType.APPLICATION_MODAL) //The serializable class does not declare a static final serialVersionUID field of the type long
            {
            	@Override
            	public void dispose()
            	{
            		System.out.println("Entered dispose");
            		super.dispose();
            		System.out.println("Exiting dispose");
            	}
            };

  4. #53
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,660
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Multiple instances of a class

    You can ignore the warning.
    Those lines do not print? Neither of them? That would mean that the dialog's .dispose() method is not being called.

    Go back to this code and try something:
    int check = 0;
                String[] options = new String[]{"Yes", "No"};
                check = JOptionPane.showOptionDialog(null,
                        "Are you sure you wish to cancel?",
                        "Attention!",
                        JOptionPane.DEFAULT_OPTION,
                        JOptionPane.PLAIN_MESSAGE, null, options,
                        options[0]);
     
     
                if(check == 0)
                {
                	dialog2.dispose();
                    frame.dispose();
                    JOptionPane.showMessageDialog(null,"dispose");
                }
    First change it to:
    int check = 0;
                String[] options = new String[]{"Yes", "No"};
                check = JOptionPane.showOptionDialog(null,
                        "Are you sure you wish to cancel?",
                        "Attention!",
                        JOptionPane.DEFAULT_OPTION,
                        JOptionPane.PLAIN_MESSAGE, null, options,
                        options[0]);
     
     
                if(check == 0)
                {
                    System.out.println("Check is 0, disposing of dialog"); // Add this
                	dialog2.dispose();
                    frame.dispose();
                    System.out.println("Disposal finished"); // And replace your JOptionPane with this
                }
    Tell me if those lines print out.
    If they do, add this:
    int check = 0;
                String[] options = new String[]{"Yes", "No"};
                check = JOptionPane.showOptionDialog(null,
                        "Are you sure you wish to cancel?",
                        "Attention!",
                        JOptionPane.DEFAULT_OPTION,
                        JOptionPane.PLAIN_MESSAGE, null, options,
                        options[0]);
     
     
                if(check == 0)
                {
                    System.out.println("Check is 0, disposing of dialog");
                    dialog2.setVisible(false); // Add this
                	dialog2.dispose();
                    frame.dispose();
                    System.out.println("Disposal finished");
                }
    And now tell me if those two lines print, and if the two lines in the dispose() method from earlier print.
    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/

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

    Lora_91 (October 25th, 2013)

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

    Default Re: Multiple instances of a class

    The lines "Check is 0, disposing of dialog" and "Disposal finished" is printed, but nothing else, and the JDialog/frame is still up. =/

  7. #55
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,660
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Multiple instances of a class

    Wait. You never call createGUI(), do you?
    That would be why dialog and frame were null many posts ago. You never initialized them.
    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/

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

    Lora_91 (October 25th, 2013)

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

    Default Re: Multiple instances of a class

    Isn't createGUI() called from MainFrame.java? That's how the whole frame is created?

                    muffin = MemberFrame.createGUI();

    Or do I need to do something more than that?

  10. #57
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,660
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Multiple instances of a class

    When is that call made?
    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/

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

    Lora_91 (October 25th, 2013)

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

    Default Re: Multiple instances of a class

    When you press the AddMemberButton:
            if(e.getSource() == AddMemberButton)
            {
                while(cancel == false)
                {
                    MA++;
                    int index = membersList.lastIndexOf(membersList);
                    int loginValue = 0;
                    Members muffin;
                    muffin = MemberFrame.createGUI();

  13. #59
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,660
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Multiple instances of a class

    Ok. Well first of all, we need to change this:
    JFrame frame = new JFrame();
        JDialog dialog1 = new JDialog();
        JDialog dialog2 = new JDialog();
    Back to this:
    JFrame frame = null;
        JDialog dialog1 = null;
        JDialog dialog2 = null;
    I know you said you were getting null pointers when you had it like that, but that was because they were never initialized like the way you wanted them to be (by the createGUI() method). Initializing them like you did to "fix" the null pointer is masking the issue. The null pointer is an indication that we did something wrong.

    Next, why are you creating a new memberFrame object in your createGUI() class? A memberFrame object must exist before you can even call that method. You do not want to create another one. Also, do you ever set frame or dialog1 visible?
    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/

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

    Lora_91 (October 25th, 2013)

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

    Default Re: Multiple instances of a class

    Ah thanks! I removed the memberFrame MF = new memberFrame();, as well as set the variables to null, and that seems to have solved the issue, the frame is being closed without any errors. =)

    I removed the dialog1, didn't seem like it was needed.

    I also checked with a message to extract the firstname from the muffin object, and it did return the name that I entered in the second frame, so the returning of the values seems to work as well.

        public Members createGUI()
        {
            frame = new JFrame(WindowName);
            dialog = new JDialog(frame, "", Dialog.ModalityType.APPLICATION_MODAL) //The serializable class does not declare a static final serialVersionUID field of the type long
            {
            	@Override
            	public void dispose()
            	{
            		System.out.println("Entered dispose");
            		super.dispose();
            		System.out.println("Exiting dispose");
            	}
            };
     
     
            dialog.setContentPane(createContentPane());
            dialog.setSize(WindowWidth,WindowHeight);
            dialog.setLocationRelativeTo(null);
            dialog.setResizable(false);
            dialog.setVisible(true);
     
            return newMember;
        }

    The only issue right now is that I can't get the right indexing, this is what I tried:

            if(e.getSource() == AddMemberButton)
            {
                while(cancel == false)
                {
                    MA++;
     
                    int loginValue = 0;
                    Members muffin;
                    muffin = MemberFrame.createGUI();
                    membersList.add(muffin);
                    JOptionPane.showMessageDialog(null,muffin.firstname);
                    int index = membersList.lastIndexOf(membersList);
     
                    String firstName = muffin.firstname;
     
                   String lastName = muffin.lastname;
                   String password = muffin.password;
     
                    UserLoginButton[index] = new JButton("Out");
                    UserLoginButton[index].setLocation(0,MA * 30 + 5);
                    UserLoginButton[index].setSize(50,20);
                    UserLoginButton[index].addActionListener(this);
                    memberPanel.add(UserLoginButton[index]);

    Error: Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1

    On the lines that is trying to refer to the index variable, I first thought it was because I hadn't added the user to the membersList yet, but even when doing that before the index int declaration it claims out of bounds.

  16. #61
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,660
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Multiple instances of a class

    I'm a little surprised the compiler lets you do this, but you have a typo:
    int index = membersList.lastIndexOf(membersList);
    If an object cannot be found in a list, it returns -1 as the index (an indication that the item cannot be found). The reason you get this result is because obviously membersList is not inside membersList. What you meant to say was:
    int index = membersList.lastIndexOf(muffin); // muffin is the member, memberList is 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/

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

    Default Re: Multiple instances of a class

    Ah, how silly of me, thanks! =)

    The only odd thing now is that another part of the code stopped working whilst we fixed the rest, it's not giving any errors or anything, the names of the users simply don't show up which they did earlier. I've messed around with it a bit and tried to find a solution, or at the very least the cause of it, but so far I haven't found anything...

            if(e.getSource() == AddMemberButton)
            {
                while(cancel == false)
                {
                    MA++;
     
                    int loginValue = 0;
                    Members muffin;
                    muffin = MemberFrame.createGUI();
     
                    membersList.add(muffin);
                    int index = membersList.lastIndexOf(muffin);            
                    String firstName = muffin.firstname;                          
                    String lastName = muffin.lastname;
                    String password = muffin.password;
     
                    UserLoginButton[index] = new JButton("Out");
                    UserLoginButton[index].setLocation(0,index * 30 + 30);
                    UserLoginButton[index].setSize(50,20);
                    UserLoginButton[index].addActionListener(this);
                    memberPanel.add(UserLoginButton[index]);
     
     
                            try
                            {
                                Image img = ImageIO.read(getClass().getResource("/images/Locked.jpg"));
                                UserLoginButton[index].setIcon(new ImageIcon(img));
                            } catch (IOException e1)
                            {
                                e1.printStackTrace();
                            }
     
                    StringMembers[index] = new JLabel(firstName + " " + lastName);
                    StringMembers[index].setLocation(70, index * 30);
                    StringMembers[index].setSize(60,30);
     
                    JOptionPane.showMessageDialog(null, index + StringMembers[index].getText());
                    memberPanel.add(StringMembers[index]);

    The buttons are created successfully with the correct distance from each other, but the JLabel StringMembers doesn't show up at all. A very weird issue since it was working earlier... I will have to go through it all again tomorrow and see if I can see what's causing it. Thank you for all the help! =)

  18. #63
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,660
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Multiple instances of a class

    I assume the JLabel's text are set after the frame has been created? If so, that is because the text of JLabels is not dynamic. You can change it, but you need to include a call to label.revalidate(); after changing the text.
    Alternatively, if it seems appropriate for your needs, there is always the option of instead using JTextFields and turning off the ability to edit them (the user can't edit them, but you can programatically). It really depends on your needs.
    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. #64
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Multiple instances of a class

    Odd, I tried both adding StringMembers[index].revalidate(); and changing it from a JLabel into a JTextfield, neither worked. =/ It's especially weird since it worked earlier, and the buttons are showing up the way they are supposed to...

    Writing out the StringMembers[index] variable gives out the correct information, setting its location to 0,0 and removing both the buttons and the title still doesn't make it show up, something must be blocking it, but even that is weird since it's on the same panel as the buttons, and even at the same location as the buttons it wouldn't show up.

  20. #65
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,660
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Multiple instances of a class

    Did you try revalidating the entire panel?
    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/

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

    Default Re: Multiple instances of a class

    No, but I found a similar solution!

                    StringMembers[index] = new JLabel(firstName + " " + lastName);     
                    StringMembers[index].setLocation(70, index * 30 + 30);
                    StringMembers[index].setSize(60,30);         
                    memberPanel.add(StringMembers[index]);
                    memberPanel.repaint();

    revalidate didn't work, but a friend of mine asked me to try using repaint instead, which did!

    Thank you for all of your help. =)

  22. #67
    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 a couple of more problems. =/

    Since I need to be able to save all the information when the program closes, and load all of the information when the program starts up, I figured I had to make another method for creating users aside from doing it manually. It works to some degree, the users are being created, as well as their buttons, their buttons are added to the actionlistener, and they must have been assigned an index value?

    Somewhere along the line something goes wrong though, because even though the buttons are added to the actionlistener, the buttons doesn't seem to have been assigned to their correct values because nothing happens when I press them aside from the message I added when any button is pressed. All of the user buttons I add manually work as they should and can log in/out with their own passwords.

    So this is when I press the "CreateExamplesButton":
    if(e.getSource() == CreateExamplesButton)
            {
            	createMember("Jaina", "Proudmoore", "123");
            	createMember("Garrosh", "Hellscream", "qwe");

    Which runs this:

        public void createMember(String firstname, String lastname, String password)
        {
            Members muffin = new Members(firstname, lastname, password);
     
            membersList.add(muffin);
            int index = membersList.lastIndexOf(muffin);           
     
            UserLoginButton[index] = new JButton("Out");
            UserLoginButton[index].setLocation(0,index * 30 + 5);
            UserLoginButton[index].setSize(50,20);
            UserLoginButton[index].addActionListener(this);
            memberPanel.add(UserLoginButton[index]);
     
            System.out.println("Adding UserLoginButton with index: " + index);
     
                    try
                    {
                        Image img = ImageIO.read(getClass().getResource("/images/Locked.jpg"));
                        UserLoginButton[index].setIcon(new ImageIcon(img));
                    } catch (IOException e1)
                    {
                        e1.printStackTrace();
                    }
     
     
            MemberLabels[index] = new JLabel(firstname + " " + lastname);    
            MemberLabels[index].setLocation(70, index * 30 );
            MemberLabels[index].setSize(200,30);        
            memberPanel.add(MemberLabels[index]);
            memberPanel.repaint();
        }

    The correct index is written out, the buttons are created as well as the JLabel with the correct name, but the button for some reason doesn't get assigned correctly, it's really odd. =/


    Also, not quite sure of how I should remove users when needed, I tried with this which uses their index:

    if(e.getSource() == RemoveMemberButton)
            {
                String removeMember = "";
                removeMember = JOptionPane.showInputDialog(null, "Who would you like to remove?");
     
     
                if(removeMember.equals(""))
                {
                    JOptionPane.showMessageDialog(null, "No user by that index; sequence aborted.");
                }else
                {
                    int muffinIndex = Integer.parseInt(removeMember);
                    if(membersList.get(muffinIndex).firstname.equals(""))
                    {
                    	JOptionPane.showMessageDialog(null, "Sorry, no user by that ID.");
                    }else
                    {
                    	JOptionPane.showMessageDialog(null,"Removing member: " + membersList.get(muffinIndex).firstname + " " + membersList.get(muffinIndex).lastname + ".");
                        membersList.remove(muffinIndex);
                        memberPanel.remove(UserLoginButton[muffinIndex]);
                        memberPanel.remove(MemberLabels[muffinIndex]);
                        UserLoginButton[muffinIndex] = null;
                        MemberLabels[muffinIndex] = null;
     
                        int loopIndex = muffinIndex;
                        while(loopIndex < membersList.size())
                        {
                            UserLoginButton[loopIndex + 1].setLocation(0, loopIndex * 30 + 5);
                            MemberLabels[loopIndex + 1].setLocation(70, loopIndex * 30);
                            loopIndex++;
                        }
                    }
     
     
                  memberPanel.repaint();
                }

    Sometimes the button and JLabel disappears and the other ones bellow are moved up one level, but for the most part the button and JLabel remains when they in actuality have been removed from the list, because the message that displays the name it is removing updates accordingly. If I create 5 unique users, and tell the program to remove the user with index 0, the first time the button and JLabel is actually removed and the rest is moved up one slot. The second time it gives me the message of removing the correct user, but the list is unaffected and I get a nullpointerexception error on:
    memberPanel.remove(UserLoginButton[muffinIndex]);

    It must be because I simply try to move them up whilst they keep the same index ID, which would require me to give them the index ID before their current one? But that would have to be done to every single ID in the list after the one that is removed... Am I over thinking this or did this get really complicated? ^^

  23. #68
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,660
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Multiple instances of a class

    I don't understand. Are the buttons not responding?
    The more I look at this, the more I think this is not the "best" way of going about it. Considering your needs, perhaps you should not be trying to manage all the buttons in a single action listener. You are requiring on a lot of cross-referencing, which can sometimes lead to some difficult-to-solve bugs.
    I'm going to suggest some code for the individual buttons for the users, and you can go with it or not. It's up to you.
    Given some basic Members class (your class is larger, but I only added what I needed for this example):
    public class Members {
    	private String username;
     
    	public void setUsername(String user) {
    		this.username = user;
    	}
    	public String getUsername() {
    		return this.username;
    	}
    }
    Now we have an abstract ActionListener class designed specifically for our Member buttons. A new instance of this will be created for each button later.
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    /**
     * MembersActionListener.java
     *
     * Oct 30, 2013
     */
    public abstract class MembersActionListener implements ActionListener {
    	@Override
    	public void actionPerformed(ActionEvent e) {
    		getMember().setUsername("name");
    		/*
    		 * TODO: this is where you would do any of the member-specific actions you would like to
    		 * happen when the member's button is pressed. The example code here is just to show how
    		 * the getMember() method can be used in the abstracted superclass.
    		 */
    	}	
    	/**
    	 * Method used by the actionPerformed() method to get the members associated with this listener
    	 * @return the member associated with this listener
    	 */
    	protected abstract Members getMember();
    }
    Now to show how this works, here is a small test class. It doesn't do anything when it runs because I didn't create a frame or anything, but if you look at the code and read the comments, you should be able to figure out how the actionListener is implemented. As long as all of the member buttons operate the same way for all members, we only need to override the getMembers() method, not the actionPerformed() method as well.
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.JButton;
    /**
     * TestClass.java
     *
     * Oct 30, 2013
     */
    public class TestClass {
    	private List<Members> membersList;
     
    	public TestClass() {
    		this.membersList = new ArrayList<Members>();
    		Members member0 = new Members();
    		member0.setUsername("someName");
    		this.membersList.add(member0);
    		JButton button0 = new JButton("Button");
    		button0.addActionListener(new MembersActionListener() {
    			@Override
    			protected Members getMember() {
    				return membersList.get(0);
    				/*
    				 * Since all members buttons work the same, we put the actionPerformed() code
    				 * in the MembersActionListener superclass and only override the getMember()
    				 * method so the actionPerformed() method in the superclass will run with the
    				 * correct members object.
    				 */
    			}
    		});
    		Members member1 = new Members();
    		member1.setUsername("someName");
    		this.membersList.add(member1);
    		JButton button1 = new JButton("Button");
    		button1.addActionListener(new MembersActionListener() {
    			@Override
    			protected Members getMember() {
    				return membersList.get(1);
    			}
    		});
    	}
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		new TestClass();
    	}
    }

    As for the null pointers, you will get that if you have null values in indexes of your array.
    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/

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

    Default Re: Multiple instances of a class

    I don't understand. Are the buttons not responding?
    After fooling around with the code for a bit I found what was causing the issue, and it is now resolved. =)

    It became a lot easier to understand when I streamlined the creation of the users into the same code, instead of keeping two different versions of it:

    if(e.getSource() == AddMemberButton)
            {             
                    Members muffin;
                    muffin = MemberFrame.createGUI();
     
                    if(muffin != null)
                    {
                    	createMember(muffin.firstname,muffin.lastname,muffin.password);	
                    }
     
            }else if(e.getSource() == CreateExamplesButton)
            {
            	createMember("Jaina", "Proudmoore", "123");
            	createMember("Garrosh", "Hellscream", "qwe");
            	createMember("Sylvanas", "Windrunner", "fgt");
            	createMember("Anduin", "Wrynn", "rtg");
            }

    Both works well and I can both log in and out without problem.

    Should I still try to change the code to work the way you suggested? I looked over it quite a bit and I think I understand it, at least most of it, and if it has a lesser risk of causing bugs then that would be great too.

    The issue that remains however is how I would go about removing users. It's a lot trickier than I thought to get the referencing right, and I'm not really sure of how to do it.

    If I have say four users:
    User1[index 0] Lisa
    User2[index 1] John
    User3[index 2] Karl
    User4[index 3] George

    Then if John for some reason needs to be removed, in the membersList everyone after him will be moved up one slot so it should be something like:
    User1[index 0] Lisa
    User3[index 1] Karl
    User4[index 2] George

    Since their index is changed, their respective buttons and all of the information connected to them must be changed as well? At first I figured I would run through all of the members before removing John, and setting the user in front of them to be equal to their own, thus moving all members from the removed member "down" one slot. But I don't seem to get it working right. =/

    if(e.getSource() == RemoveMemberButton)
            {
                String removeMember = "";
                removeMember = JOptionPane.showInputDialog(null, "Who would you like to remove?");
     
     
                if(removeMember.equals(""))
                {
                    JOptionPane.showMessageDialog(null, "No username submitted; sequence aborted.");
                }else
                {
                    int muffinIndex = Integer.parseInt(removeMember);
                    if(membersList.size()-1 < muffinIndex)
                    {
                    	JOptionPane.showMessageDialog(null, "Sorry, no user by that ID.");
                    }else
                    {
                    	JOptionPane.showMessageDialog(null,"Removing member: " + membersList.get(muffinIndex).firstname + " " + membersList.get(muffinIndex).lastname + ".");
                        int index = membersList.size() - 1;
     
                    	membersList.remove(index);
                        memberPanel.remove(UserLoginButton[index]);
                        memberPanel.remove(MemberLabels[index]);
     
     
     
                        int k = muffinIndex;
                        while(k < membersList.size())
                        {
                        	UserLoginButton[k+1] = UserLoginButton[k];
                        	MemberLabels[k+1] = MemberLabels[k];
                            k++;
                        }
     
                        UserLoginButton[index] = null;
                        MemberLabels[index] = null;
                    }
     
     
                  memberPanel.repaint();
                }
                memberPanel.revalidate();
            }

    It seems to work if I wish to remove the last member in the list, but not if I want to remove someone in the middle.

  25. #70
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,660
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Multiple instances of a class

    It is entirely up to you. I think the way I suggested would remove the need for the you to figure out which button goes with which user (since that would be set when you add the action listener to the button).

    If you want an array with a changing length, you should use a List instead of an array (like you are doing with your membersList).
    An alternative solution, if you wanted your User and their button and label to be properly linked would be to use a Map. If the order of your users matter, a LinkedHashMap is what you want. The downside to this is that you cannot do normal indexing, since the lack of ordering in Maps defeats the purpose of being able to retrieve objects with indexes.
    Since you would want to Map the User to a button and a label, you would need to create a little class like this:
    public class Pair {
        public JButton button;
        public JLabel label;
        public Pair(JButton but,JLabel lab) {
            button = but;
            label = lab;
        }
    }
    The Pair would be your Map values. You would add the Members key and Pair values to the map like this:
    LinkedHashMap<Members,Pair> membersMap = new LinkedHashMap<Members,Pair>();
    ...
    Members member = new Members(...);
    JButton button = new JButton(...);
    JLabel label = new JLabel(...);
     
    Pair pair = new Pair(button,label);
    membersMap.put(member,pair);
    Then, as long as you have a Members object, you can get its Button/Label Pair by saying:
    Members member = ...; // Some members object
    Pair pair = membersMap.get(member);
    JButton button = pair.button;
    JLabel label = pair.label;

    Using this mechanism allows you to get rid of all of your separate arrays and lists for Members, JButtons, and Labels and combines them all into a single data structure, where the buttons and labels are directly mapped to a specific Members object.
    If you wanted to get a list of the Members in your Map and loop through them, you would have to do it this way (remember, no indexes):
    LinkedHashMap<Members,Pair> membersMap = new LinkedHashMap<Members,Pair>();
    // Assume you added members and pairs after this
    ...
    for(Members member : membersMap.keySet()) {
    	System.out.println(member.getUsername());
    }

    The downside to this is that you cannot directly reference the JButtons for the Members without first knowing the Members object you want the JButton for (well, you can, but it is ugly). Depending on what you want to accomplish, there are probably ways around that issue.
    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. #71
    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 come to the conclusion that I need to change it to work the way you suggested, because the current referencing refuses to cooperate the way I would like it to. =/

    MemberFrame.java (creation of user and therefor also button):

       public void createMember(String firstname, String lastname, String password)
        {
        	ID++;
            Members muffin = new Members(firstname, lastname, password, ID);
     
     
            membersList.add(muffin);
            int index = membersList.lastIndexOf(muffin);         
     
            UserConfigurationButton[ID] = new JButton("Out");
            UserConfigurationButton[ID].setLocation(0,index * 30 + 5);
            UserConfigurationButton[ID].setSize(50,20);
            UserConfigurationButton[ID].addActionListener(new membersActionListener() 
            {
            	@Override
            	protected Members getMember() //There was an error here: "The method getMember() of type new membersActionListener(){} must override or implement a supertype method"
    //But it offered a solution which I'm rather uncertain of since your code didn't have it, nevertheless that part seems to work for now.
     
     
            	{
            		//JOptionPane.showMessageDialog(null,ID);
            		return membersList.get(ID); //One of the issues is here, for whatever reason all of the created buttons refer to the last
     //created button, even though they are all created one by one, and they should all have their own value... Using "0" instead of "ID" meant
     //all of the buttons referred to the first button created.
    //"ID" is currently an integer variable that I'm trying to use to help differentiate all of the users, whenever a user is created the "ID" integer
    // increases by one, and never decreases. The ID is also stored in the Members.java together with the name and everything else, the idea 
    //being that I try to never refer to the users by their index, this made it difficult to listen to their buttons however.
            	}
    		});
            memberPanel.add(UserConfigurationButton[ID]);



    membersActionListener.java:

    package LoginSystem;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    import javax.swing.*;
     
    public abstract class membersActionListener implements ActionListener
    {
    	userConfiguration UserConfiguration = new userConfiguration();
    	@Override
    	public void actionPerformed(ActionEvent e)
    	{
    		//getMember().setFirstName("Temporary name");
     
    		//UserConfiguration.createGUI(); //Different class I made which creates a GUI whenever the user configuration button is
    // pressed, or that is the idea at the very least once I get this part working. Since I'm going to use this class however it might be better to
    // move all of that code here, but I want to make sure this starts to work first.
     
    		JOptionPane.showMessageDialog(null,getMember().firstname); //I'm using this to see what the button is referring too, and it
    // always gives the same name no matter which button I press, as I mentioned above in MainFrame.java.
    		//protected abstract Members getMember(); //Multiple markers at this line:
    //	"Syntax Error, insert "enum Identifier" to complete EnumHeader"
    //	"Syntax error, insert "EnumBody" to complete BlockStatement"
    //	"Syntax error on token "Members", @ expected
    	}
     
    	//This method was added by eclipse after the error in MainFrame.java, it refused to work without it.
    	protected Members getMember() {
    		// TODO Auto-generated method stub
    		return null;
    	}
     
     
     
    }

    I added some comments amidst the code, it might have gotten a bit messy, if so I apologize, but it felt a lot easier to explain every part on their own that way.

    I'm currently not receiving any errors but all of the buttons return the same value as of currently, and I'm unsure of what I did wrong. =/

    If there is anything that is unclear or you need to see other parts of the code, as always feel free to ask! =)

  27. #72
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,660
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Multiple instances of a class

    In the abstract action listener, you do not need to return anything from the method. You just declare it with the abstract keyword: protected abstract Members getMembers();

    Also, I realized a better implementation. There is no reason we cannot set the Member for the action listener in a constructor. So your MembersActionListener would become this (notice it is not abstract):
    public class MembersActionListener implements ActionListener {
    	private Members member;
     
    	public MembersActionListener(Members memb) {
    		member = memb;
    	}
     
    	public Members getMember() {
    		return member;
    	}
     
    	@Override
    	public void actionPerformed(ActionEvent e) {
    		JOptionPane.showMessageDialog(null,getMember().firstname);
    	}
    }

    And you would implement it like this (far more simple):
    Members someMember = ...;
    JButton button = new JButton("Some button");
    button.addActionListener(new MembersActionListener(someMember));
    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/

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

    Default Re: Multiple instances of a class

    Alright, thanks, that works great! =)

    Sorry for the slow response, I've been a little busy with other projects so I didn't have much time to look over the coding the past few days.
    _________________

    So I merged the userConfiguration.java class with the membersActionListener.java class, and all of it seems to work rather well with the exception of one thing. I need to use a method in the membersActionListener.java class which is in the MainFrame.java class, without making MainFrame.java static since I wish to avoid that. Previously we created another instance of the class and thus got access to all of its variables and methods, but in the case of MainFrame.java this also creates new instances of the JFrames (thus opening up new instances of the program itself).

    I'm not sure if there is a way around this? Or if I should try to do it in the MainFrame.java class instead? But that gets a bit tricky since then I need to do the whole referencing part again. =/

    Within MainFrame.java:
        public int getIndexOfMember(int incomingID)
        {
            for(int i = 0; i < ID; i++)
            {
                if(membersList.get(i).ID == incomingID)
                    JOptionPane.showMessageDialog(null,membersList.get(ID).firstname + " has the ID: " + incomingID + " - ");
                	return i;
            }
            return -1;
        }
     
     
        public void removeMember(int incomingID)
        {
           // membersList.remove(getMemberFirstName(username));
           membersList.remove(getIndexOfMember(incomingID));
        }

    Within membersActionListener.java:
    	@Override
    	public void actionPerformed(ActionEvent e)
    	{
    		JOptionPane.showMessageDialog(null,getMember().firstname);
     
    		if(e.getSource() == removeUserButton)
            {
    		int confirmationTerminate = 0;
    			String[] options = new String[]{"Yes", "No"};
    			confirmationTerminate = JOptionPane.showOptionDialog(null,
                    "Are you sure you wish to terminate your account?",
                    "Attention!",
                    JOptionPane.DEFAULT_OPTION,
                    JOptionPane.PLAIN_MESSAGE,
                    null, options, options[0]);
     
    			if(confirmationTerminate == 0)
    			{
    				String confirmationPassword = JOptionPane.showInputDialog(null,"Enter your password:");
    				if(confirmationPassword.equals(getMember().password))
                	{
    					removeMember(ID); //This is where I wish to refer to the method in the MainFrame.java class
                	}

  29. #74
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,660
    Thanks
    25
    Thanked 325 Times in 302 Posts

    Default Re: Multiple instances of a class

    The easiest way would be to add a variable in your membersActionListener class like this:
    public MainFrame mainFrame;
    And then set the variable (either by passing the value in constructor like we did with the members variable or some other way) when you create your membersActionListener object.
    There may be a more complex way of doing it, by getting the source of the ActionEvent and reversing through the button's parent containers until the MainFrame is reached, but that is an unnecessary amount of complexity when you could just pass the instance of the MainFrame object.
    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/

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

    Default Re: Multiple instances of a class

    Hm, not quite sure of what you mean with passing the value in a constructor, which members are you referring to?

Page 3 of 4 FirstFirst 1234 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, 09:46 PM
  3. Multiple class instances ??? But how ???
    By dumb_terminal in forum Object Oriented Programming
    Replies: 6
    Last Post: December 2nd, 2010, 07:42 AM
  4. Replies: 0
    Last Post: December 1st, 2010, 05: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