Reputation:
The code shown below does work because the method values()
is static. My question is how can I achieve what the code below would do if B was not generic.
class A<B extends Enum<B>> {
public A() {
for (B b : b.values()) {
}
}
}
I can think of two solutions:
Both seem messy to me. Anyone have any better solutions?
Upvotes: 3
Views: 149
Reputation: 27886
Here's a stripped-down example involving a subclass of JPanel that let's you choose a value from an Enum using radio buttons. To use it you'd do something like:
enum Animal { DOG, CAT, FISH };
RadioPanel<Animal> animal_panel = new RadioPanel<Animal>(Animal.class);
dialog.add(animal_panel);
...
Animal favorite_animal = animal_panel.getSelectedOption();
The class itself:
public class RadioPanel<T extends Enum<T>> extends JPanel {
private Map<T,JRadioButton> buttons;
private ButtonGroup button_group;
private Class<T> clazz;
public RadioPanel(Class<T> clazz) {
this.clazz = clazz;
buttons = new EnumMap<T, JRadioButton>(clazz);
button_group = new ButtonGroup();
for (T value : clazz.getEnumConstants()) {
JRadioButton button = new JRadioButton(value.toString());
buttons.put(value, button);
button_group.add(button);
add(button);
}
}
public void setSelectedOption(T value) {
buttons.get(value).setSelected(true);
}
public T getSelectedOption() {
for (T value : clazz.getEnumConstants()) {
if (buttons.get(value).isSelected())
return value;
}
return null;
}
}
Upvotes: 1