JavaFX中getChildren().removeAll()无法移除节点问题排查
JavaFX中removeAll()无效的原因及修复方案
问题1:removeAll()调用方式错误
JavaFX容器的getChildren()返回的是ObservableList,这个集合的removeAll()方法必须传入要移除的元素或集合,空参数的removeAll()不会执行任何移除操作(甚至编译阶段就会报错,因为没有对应重载)。如果要清空所有子元素,应该用clear()方法。
问题2:createButton方法缺少返回值
你的createButton方法声明返回Button,但代码里没有写return button;,导致每次调用这个方法都返回null,往容器里加的是无效的空元素,这也是按钮没法正确替换的关键原因。
修复后的完整代码
public class App extends Application { public static void main(String[] args) { launch(); } private int count; public void start(Stage stage) { count = 0; var root = new VBox(); var button = createButton(root); root.getChildren().add(button); var scene = new Scene(root, 640, 480); stage.setScene(scene); stage.show(); } private void onButtonClicked(final Pane root) { count += 1; root.getChildren().clear(); // 用clear()替代无效的removeAll() root.getChildren().add(createButton(root)); } private Button createButton(final Pane root) { var button = new Button("Clicked " + count + " times"); button.setOnAction((_event) -> onButtonClicked(root)); return button; // 补上返回按钮实例的代码 } }
额外优化:无需反复创建新按钮
其实没必要每次点击都销毁旧按钮、创建新按钮,直接修改现有按钮的文本更高效:
public class App extends Application { public static void main(String[] args) { launch(); } private int count; public void start(Stage stage) { count = 0; var root = new VBox(); var button = new Button("Clicked " + count + " times"); button.setOnAction(_event -> { count++; button.setText("Clicked " + count + " times"); }); root.getChildren().add(button); var scene = new Scene(root, 640, 480); stage.setScene(scene); stage.show(); } }
这种写法代码更简洁,性能也更好。
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

