有什么办法可以将文本水平居中放置javafx.scene.control.ChoiceBox
?我希望将文本放在中ChoiceBox
,以及在选择值的过程中打开的下拉列表中居中。
根据@VGR的建议,我将实现更改为使用javafx.scene.control.ComboBox
。然后,我创建了一个名为CenteredListCell
:
import javafx.geometry.Pos;
import javafx.scene.control.ListCell;
public class CenteredListCell<T> extends ListCell<T> {
/** Default constructor */
public CenteredListCell() {
setMaxWidth(Double.POSITIVE_INFINITY);
setAlignment(Pos.BASELINE_CENTER);
}
@Override
public void updateItem(final T item, final boolean empty) {
super.updateItem(item, empty);
setText(empty || item == null ? null : item.toString());
}
}
接下来,我创建了以下实用程序方法(感谢@kleopatra带来了灵感runWhenSkinned
):
private static void runWhenSkinned(final Control control, final Runnable operation) {
final ReadOnlyObjectProperty<?> skinProperty = control.skinProperty();
if (skinProperty.get() == null) {
// Run after the control has been skinned
skinProperty.addListener(observable -> Platform.runLater(operation));
} else {
// Run now, since the control is already skinned
operation.run();
}
}
public static <T> void center(final ComboBox<T> comboBox) {
runWhenSkinned(comboBox, () -> {
// Get the width of the combo box arrow button
final Region arrow = (Region)comboBox.lookup(".arrow-button");
final double arrowWidth = arrow.getWidth();
// Create a centered button cell
final ListCell<T> buttonCell = new CenteredListCell<T>();
comboBox.setButtonCell(buttonCell);
// Create an insets object with uneven horizontal padding
final Insets oldPadding = buttonCell.getPadding();
final Insets newPadding = new Insets(oldPadding.getTop(),
arrowWidth, oldPadding.getBottom(), 0);
// Replace the default cell factory
comboBox.setCellFactory(listView -> new CenteredListCell<T>() {
{ setPadding(newPadding); }
});
});
}
最终结果是ComboBox
在按钮单元格和项目列表视图中居中显示文本。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句