How to get SimpleComboBox to display my default value

Thom picture Thom · Dec 20, 2012 · Viewed 7.8k times · Source

I have a loop that builds our questionnaires. I have a function that I call the builds the correct type. Here's the section that builds the combo box:

Field<?> field = null;
if (item instanceof MultipleChoiceQuestionDTO) {
  MultipleChoiceQuestionDTO multipleChoice = (MultipleChoiceQuestionDTO) item;
  SimpleComboBox<String> cmbQuestion = new SimpleComboBox<String>();
  String prompt = multipleChoice.getPrompt();
  cmbQuestion.setFieldLabel(ImageViewer.formatPrompt(prompt));
  List<String> choices = new ArrayList<String>();
  choices.add(prompt);
  for (String choice : multipleChoice.getPossibleAnswers()) {
    choices.add(choice);
  }
  cmbQuestion.add(choices);
  cmbQuestion.setEditable(false);
  cmbQuestion.setForceSelection(true);
  cmbQuestion.setSimpleValue(prompt);
  field = cmbQuestion;
}

I want to set the default answer to the prompt so that I can test for that later. The problem is that this is not setting the selected value on my combo box. What am I missing?

Answer

sanbhat picture sanbhat · Dec 27, 2012

Assuming that you have an "answer". You can get the index of it from the List<String> choices.

int answerIndex = choices.indexOf(answer);
simpleComboBox.select(answerIndex);

Or you can directly use simpleComboBox.select(answer); in case of String

If you would like to show a default text, then you can use

simpleComboBox.setEmptyText("Select an answer....");