java - 如何在 javafx 中隐藏/显示动态创建的节点?
问题描述
我已经动态创建了多个节点。现在,我必须在单击时找到特定节点,它必须隐藏窗格中的所有其他节点。此外,当我再次单击它时,它应该显示隐藏节点。
例如,在附图中,单击根节点上的向下箭头图标,必须隐藏所有其他节点,第二次单击时,必须再次显示隐藏的节点。这就是我创建按钮的方式。
Node_Basic_Event_Node anode = new Node_Basic_Event_Node(calcNode_Id("Basic_Event_Node"), "Basic_Event_Node", editorName, editorType); anode.relocate(50, 50); elementsContent.getChildren().add(anode);
现在,单击图像中根节点的向下箭头图标时如何隐藏节点?我尝试了这个代码示例,但它隐藏了所有节点,包括“根节点”
Pane elementsContent = (Pane) getParent();
for (Node node : elementsContent.getChildren()) {
node.managedProperty().set(true);
node.setVisible(false);
}
解决方案
我不确定您的问题到底出在哪里,但是我创建了一个小示例,希望对您有所帮助。不应该改变可见性的按钮(这里:某些文本)每次都被简单地过滤掉。
package sample;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.Optional;
import java.util.Random;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
VBox vBox = new VBox();
Random random = new Random();
int randomIndex = random.nextInt(10);
String chosen = "The Chosen One", simple = "Simple Button";
for (int i = 0; i < 10; i++) {
Button button = new Button(simple);
if (i == randomIndex)
button.setText(chosen);
vBox.getChildren().add(button);
button.setOnAction(event -> {
Button clickedButton = (Button) event.getSource();
if (clickedButton.getText().equals(chosen)) {
// Save visibility status of the simple buttons:
Optional<Boolean> visible = vBox.getChildren().stream()
.filter(node -> node instanceof Button)
.map(node -> (Button) node)
.filter(btn -> !btn.getText().equals(chosen))
.findFirst().map(Button::isVisible);
// Change visibility of the buttons except the filtered chosen one:
vBox.getChildren().stream()
.filter(node -> node instanceof Button)
.map(node -> (Button) node)
.filter(btn -> !btn.getText().equals(chosen))
.forEach(btn -> btn.setVisible(!btn.isVisible()));
// Change the (not so) chosen one:
if (visible.isPresent() && !visible.get()) {
int nextIndex = random.nextInt(10);
for (int j = 0; j < vBox.getChildren().size(); j++) {
if (vBox.getChildren().get(j) instanceof Button) {
Button btn = (Button) vBox.getChildren().get(j);
if (j == nextIndex)
btn.setText(chosen);
else
btn.setText(simple);
}
}
vBox.requestFocus();
}
}
});
}
primaryStage.setScene(new Scene(vBox));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
推荐阅读
- autodesk-forge - 如何从 Forge Viewer 中检索文件名?
- javascript - 有没有一种简单的方法可以用 javascript/jquery 倒带 html 视频元素?
- java - Api Gateway 是否允许没有请求正文的发布请求
- bash - 在没有退出调用的情况下将 bash 脚本粘贴到控制台
- java - 无法通过 Spring 从 Redis 获得正确的值
- xamarin.forms - 轻按时 UWP 上的 Xamarin TextCell 会移动
- sql - Clickhouse 加入条件
- kubernetes - 使用 Prometheus Operator 监控自定义 kubernetes pod 指标
- javascript - 如何使用 vue.js 和 d3.js 加载 csv 文件
- javascript - 如何使 Material UI React 组件中的按钮粘在底部?