Search code examples
javaarraysswingjcombobox

Best way to construct a JComboBox?


So I have a program wherein the user is able to select different teams from a dropdown list; here is the code for the JComboBox:

JComboBox<String> homeSelector = new JComboBox<String>(this.getTeamNames(Team.teamList));

teamList is a public static ArrayList belonging to the public Team class and stores all of the selectable teams; which is initialized from the app's files on startup(I'm not using a database for this application). So here is the problem I'm encountering: I know JComboBox can take a String[] argument to automatically generate the selection options for the user, however I'm having a hard time actually producing a String[] programmatically. To see what I mean, here is my code for the getTeamNames() method seen above:

private Object[] getTeamNames(ArrayList<Team> teams) {
        ArrayList<String> teamNames = new ArrayList<String>();
        for(int i = 0; i < teams.size(); i++) {
            Team selected = teams.get(i);
            String name = selected.getName();
            teamNames.add(name);
        }
        return teamNames.toArray();
    }

As you can see, getTeamNames() returns an Object[], which is a type mismatch from String[], I know. The reason for this is because before I had the method returning a String[]; but because the toArray() method always returns an Object[], I was attempting to cast Object[] to String[](like this: (String[])teamList.toArray()) which is just fine according to my IDE but causes the program to crash with error "Class cast exception". But on the other hand, it's clearly not working with the Object[] either, because the argument Object[] is undefined for the JComboBox() constructor.

So what I want to know is, is there a better way to do this? Preferably without having to manually hard-code in all of the team data, because that would really suck(not to mention that this would certainly not be a clean or elegant solution). Only problem is I can't see how you would go about making a standalone Array object programmatically(is this even possible in Java?), as the Array class seems to always be married to an interface(i.e. ArrayList, ArrayDeque, etc.) and these are not legal arguments for the JComboBox constructor either. As always, any and all help is greatly appreciated.


Solution

  • You can create JComboBox<Team> because what the JComboBox displays is the string returned by method toString of (in your case) class Team. Hence override method toString in class Team and have it return the team name.

    public class Team {
        String name;
    
        public String toString() {
            return name;
        }
    }
    

    Hence you can create the JComboBox like so.

    JComboBox<Team> homeSelector = new JComboBox<Team>(Team.teamList.toArray(new Team[0]));