我想创建一个按钮事件来创建列表。在此列表中,滚动条 应该被移动。但我成了一个错误,因为查找方法只能在渲染后使用。
HBox root = new HBox();
Button b = new Button("initList");
b.setOnAction(e->
{
ListView<String> list = new ListView<String>();
for (int i = 0; i < 20; i++)
{
list.getItems().add(i+"");
}
ScrollBar bar = (ScrollBar) list.lookup(".scroll-bar");
bar.setValue(0.5);
root.getChildren().add(list);
});
root.getChildren().add(b);
Scene scene = new Scene(root,400,400);
primaryStage.setScene(scene);
primaryStage.show();
答案 0 :(得分:0)
为确保在布局后调用,您可以使用runLater
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class LookupTest extends Application {
@Override
public void start(Stage primaryStage) {
HBox root = new HBox();
Button b = new Button("initList");
b.setOnAction(e ->
{
ListView<String> list = new ListView<String>();
for (int i = 0; i < 20; i++) {
list.getItems().add(i + "");
}
Platform.runLater(() -> {
ScrollBar bar = (ScrollBar) list.lookup(".scroll-bar");
if (bar != null) bar.setValue(0.5);
});
root.getChildren().add(list);
});
root.getChildren().add(b);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}