我有一个带有多个文本选项的 JavaFX ComboBox。如果选项使用居中对齐而不是左对齐就好了,但我还没有想出如何做到这一点。
以下是我使用的样式。我添加了子句“-fx-text-alignment:center;”但它对字符串在组合框中的位置没有影响。
normalStyle = "-fx-font-family:san serif;"
+ "-fx-font-size:12;"
+ "-fx-text-alignment:center;"
+ "-fx-font-weight:normal;";
样式附加到组合框如下:
cbChoices.setStyle(normalStyle);
我注意到组合框条目的大小和粗细会响应上述变化,但不会响应对齐方式。
我不想在字符串的开头添加空格来让它们对齐。还有别的办法吗?
最佳答案
您需要为 ComboBox
中的每个 ListCell
设置样式,而不是 ComboBox
本身。
您可以通过使用 setCellFactory()
方法提供您自己的 ListCell
实现来做到这一点:
// Provide our own ListCells for the ComboBox
comboBox.setCellFactory(lv -> new ListCell<String>() {
// We override the updateItem() method
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
// Set the style for this ListCell
setStyle("-fx-alignment: center");
// If there is no item for this cell, leave it empty, otherwise show the text
if (item != null && !empty) {
setText(item);
} else {
setText(null);
}
}
});
Sample Application:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ComboBoxAlignment extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// Simple interface
VBox root = new VBox(5);
root.setPadding(new Insets(10));
root.setAlignment(Pos.CENTER);
// Simple ComboBox with items
ComboBox<String> comboBox = new ComboBox<>();
comboBox.getItems().addAll("Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet");
// Provide our own ListCells for the ComboBox
comboBox.setCellFactory(lv -> new ListCell<String>() {
// We override the updateItem() method
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
// Set the style for this ListCell
setStyle("-fx-alignment: center");
// If there is no item for this cell, leave it empty, otherwise show the text
if (item != null && !empty) {
setText(item);
} else {
setText(null);
}
}
});
root.getChildren().add(comboBox);
// Show the Stage
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
The Result:
关于java - 组合框选项中的文本对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54585710/