單選

單選組件要求使用者從列表中選擇一個項目。它類似於簡單的下拉式選單實作。以下列表顯示了一個範例

@ShellComponent
public class ComponentCommands extends AbstractShellComponent {

	@ShellMethod(key = "component single", value = "Single selector", group = "Components")
	public String singleSelector() {
		SelectorItem<String> i1 = SelectorItem.of("key1", "value1");
		SelectorItem<String> i2 = SelectorItem.of("key2", "value2");
		List<SelectorItem<String>> items = Arrays.asList(i1, i2);
		SingleItemSelector<String, SelectorItem<String>> component = new SingleItemSelector<>(getTerminal(),
				items, "testSimple", null);
		component.setResourceLoader(getResourceLoader());
		component.setTemplateExecutor(getTemplateExecutor());
		SingleItemSelectorContext<String, SelectorItem<String>> context = component
				.run(SingleItemSelectorContext.empty());
		String result = context.getResultItem().flatMap(si -> Optional.ofNullable(si.getItem())).get();
		return "Got value " + result;
	}
}

以下螢幕錄影展示了單選組件的典型輸出

上下文物件是 SingleItemSelectorContext。下表描述了其上下文變數

表 1. SingleItemSelectorContext 範本變數
描述

當組件存在時,返回的值。

可見項目,其中列包含名稱和選定項目的映射。

模型

父上下文變數 (請參閱 SelectorComponentContext 範本變數)。

您可以預先選取一個項目,方法是定義它以公開。如果您知道預設值,並讓使用者只需按下 Enter 即可做出選擇,這會很有用。以下列表設定了預設值

SelectorItem<String> i1 = SelectorItem.of("key1", "value1");
SelectorItem<String> i2 = SelectorItem.of("key2", "value2");
List<SelectorItem<String>> items = Arrays.asList(i1, i2);
SingleItemSelector<String, SelectorItem<String>> component = new SingleItemSelector<>(getTerminal(),
		items, "testSimple", null);
component.setDefaultExpose(i2);