gpt4 book ai didi

java - 在javafx中按字母顺序选择节点

转载 作者:行者123 更新时间:2023-11-30 07:05:39 24 4
gpt4 key购买 nike

enter image description here

根据图像,有 20 个切换按钮。我想按字母顺序更改按键的焦点遍历。如果我从键盘按 V,那么它将选择第一个出现(VVS1),如果第二次它将选择第二个出现(VVS2) )。

最佳答案

迭代切换开关,如果发现其中包含适当的文本,则将选定的切换开关更改为该节点:

private static Node[] fromStrings(ToggleGroup group, String... strings) {
Node[] result = new Node[strings.length];

for (int i = 0; i < strings.length; i++) {
ToggleButton button = new ToggleButton(strings[i]);
button.setPrefSize(100, 50);
button.setTextAlignment(TextAlignment.CENTER);
button.setToggleGroup(group);
result[i] = button;
}

return result;
}

@Override
public void start(Stage primaryStage) {
GridPane root = new GridPane();
final ToggleGroup group = new ToggleGroup();
root.addRow(0, fromStrings(group, "If", "VVS1", "VVS2", "VS1", "VS2", "SI1", "SI2", "SI2-", "SI3", "SI3-"));
root.addRow(1, fromStrings(group, "I1", "I1-", "I2", "I2-", "I3", "I4", "I5", "I6", "I7", "I8"));

root.setFocusTraversable(true);
root.setOnKeyTyped(new EventHandler<KeyEvent>() {

@Override
public void handle(KeyEvent event) {
String s = event.getCharacter().toUpperCase();
// move focus to the next matching element
if (s.length() == 1) {
event.consume();
List<Toggle> toggles = group.getToggles();
int selectedIndex = toggles.indexOf(group.getSelectedToggle());
int size = toggles.size();

// search next matching node starting directly after the
// selected position
for (int i = selectedIndex + 1; i < size; i++) {
Toggle l = toggles.get(i);
if (((Labeled)l).getText().toUpperCase().startsWith(s)) {
group.selectToggle(l);
return;
}
}
for (int i = 0; i < selectedIndex; i++) {
Toggle l = toggles.get(i);
if (((Labeled)l).getText().toUpperCase().startsWith(s)) {
group.selectToggle(l);
return;
}
}
}
}
});

Scene scene = new Scene(root);
root.requestFocus();

primaryStage.setScene(scene);
primaryStage.show();
}

关于java - 在javafx中按字母顺序选择节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40188206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com