Jump to content

Accessing an ArrayList from a different class

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
lor

lor

    Programming Goddess

  • Members
  • PipPipPipPipPipPipPip
  • 884 posts
Hey there,

I'm building a "Who Wants to be a Millionaire" GUI, client/server game at the moment and I'm trying to access an ArrayList called randomQuestions (which is situated within a Questions class) from my WWTBAMJFrameForm (WWTBAM = Who Wants to be a Millionaire if you're wondering what that acronym means) class so I can display a randomized question within a text box on the form.
Not 100% sure how to go about this, any help if appreciated.
If you would like to see my code so far (haven't gotten very far - only really began today) then that's no problem, just request.

Cheers.


#2
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
You need to have a reference to the Question class inside your WWTBAMJFrameForm, and the Question class must allow the access to the ArrayList - which must be "public", or Question class could have getRandomQuestions() method, which gives you the reference to the List.

for example:
import java.util.ArrayList;

public class Test{
    public static void main(String[] args) {
        Question q = new Question();
        
        // ACCESS THE ARRAYLIST.
        ArrayList<Question> questions = q.getQuestionList();
        
    }    
}


class Question{
    private ArrayList<Question> randomQuestions = new ArrayList<Question>();
    
    public ArrayList<Question> getQuestionList(){
        return randomQuestions;
    }
}



#3
lor

lor

    Programming Goddess

  • Members
  • PipPipPipPipPipPipPip
  • 884 posts
Thanks for the help Sinipull, I managed to pass my array list to my other class based from your help last week.

Also, just an update: When I tried displaying my array list to a textbox within the WWTBAMJFrameForm class, in main, it has a spaz. I learned that main should only be used to initialize the form and possibly a few other things, not trying to add text to text boxes and functionality to other things. And also trying to display text to a text box without any action is not a very good idea so I've had to implement a "Next question" button, obviously set to false if they haven't answered the current question though.