fakataha
fakataha

Reputation: 800

screen ComboBoxModel based on an enum value

I'm trying to populate a combo box using enums based on a player's enum.

For example, upon initializing the game, the player chooses a faction (FactionType). The FactionType enum is used in the enum values of each unit (ShipType). The ShipType(FactionType) enum so that each ship can be switched for the appropriate object and instantiated. The problem I'm having is how to populate the combo box with ONLY the units of that faction that the player has chosen. Example code below:

public enum FactionType {
faction1, faction2, faction3
}

public enum ShipType {
Ship1(faction1), Ship2(faction2), Ship3(faction3)

private FactionType faction;

private ShipType(FactionType faction)
this.faction = faction;
}

public FactionType getFaction() {
return this.faction
}

so is it possible to create a ComboBoxModel after filtering out any unit type that isn't of the player's faction? Normally I would just make a conditional statement to check player.faction = faction but not entirely certain how to create the ComboBoxModel so any help is appreciated.

Upvotes: 0

Views: 174

Answers (2)

trashgod
trashgod

Reputation: 205795

Instead of separate enum classes, consider an EnumSet for each faction, as outlined here.

public enum Ship {

    Unit1, Unit2, Unit3, Unit4, Unit5, Unit6;
    public static Set<Ship> factionOne = EnumSet.range(Unit1, Unit5);
    public static Set<Ship> factionTwo = EnumSet.allOf(Ship.class);
}
...
DefaultComboBoxModel modelOne = new DefaultComboBoxModel();
for (Ship ship : Ship.factionOne) {
    modelOne.addElement(ship);
}

Upvotes: 1

fakataha
fakataha

Reputation: 800

I believe I've over complicated my code.

Instead of having a FactionType and ShipType, it would be simpler to split the factions into separate enums. so that each factions data is better encapsulated and simpler to set for the combo box model. so now my enums will look like so:

public enum factionOne {

unit1, unit2, unit3, unit4, unit5;

}

public enum factionTwo {

unit1, unit2, unit3, unit4, unit5, unit6;

}

etc......

Upvotes: 0

Related Questions