如何在JavaFX选择框中水平居中放置文本
有没有办法在如何在JavaFX选择框中水平居中放置文本,java,javafx,javafx-8,Java,Javafx,Javafx 8,有没有办法在javafx.scene.control.ChoiceBox中水平居中放置文本?我希望将选择框中的文本居中,以及在选择值的过程中打开的下拉列表。根据@VGR的建议,我将实现更改为使用javafx.scene.control.ComboBox。然后,我创建了一个名为CenteredListCell的类: import javafx.geometry.Pos; import javafx.scene.control.ListCell; public class CenteredList
javafx.scene.control.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());
}
}
最终结果是一个组合框
,在按钮单元格和项目列表视图中文本居中。一个选项是使用组合框,并设置其cellFactory和buttonCell属性。您可以向组合的skin属性注册一个侦听器,并在收到新外观通知时调用实用程序方法
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); }
});
});
}