我正在尝试将列表视图的内容居中对齐
private ListView<String> library = new ListView<String>();
ObservableList<String> libraryList = FXCollections.<String>observableArrayList();
我已经找到了用CSS和XML来做这件事的方法,但是我正在寻找用java做这件事的方法,有人知道吗?
发布于 2018-07-29 03:07:03
您将需要对ListView
使用自定义CellFactory
和自定义ListCell
。
下面是一个完整的示例:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// Simple UI
VBox root = new VBox(10);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(10));
ListView<String> listView = new ListView<>();
// Setup the cell factory for the listview. It will hold lists of HBoxes that can be aligned
listView.setCellFactory(stringListView -> new CenteredListViewCell());
// Sample data
listView.getItems().setAll("One", "Two", "Three", "Four");
root.getChildren().add(listView);
// Show the stage
primaryStage.setScene(new Scene(root));
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.show();
}
}
final class CenteredListViewCell extends ListCell<String> {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
// Create the HBox
HBox hBox = new HBox();
hBox.setAlignment(Pos.CENTER);
// Create centered Label
Label label = new Label(item);
label.setAlignment(Pos.CENTER);
hBox.getChildren().add(label);
setGraphic(hBox);
}
}
}
您要做的是创建一个使用HBox
作为其主要内容的自定义CenteredListViewCell
。通过设置HBox
的对齐方式,您可以将Label
居中。
然后在控制器中有了listView.setCellFactory(stringListView -> new CenteredListViewCell());
,您就告诉ListView
使用自定义单元而不是标准的Java实现。
这可能会被简化,我欢迎评论和编辑!
https://stackoverflow.com/questions/51574266
复制相似问题