import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
public class CustomComboBox extends ComboBox {
public CustomComboBox() {
super();
}
public CustomComboBox(ObservableList items) {
super(items);
}
public BooleanProperty centeredProperty() { return centered; }
public final void setCentered(boolean value) { centeredProperty().set(value); }
public final boolean isCentered() { return centeredProperty().get(); }
private BooleanProperty centered = new SimpleBooleanProperty(this, "centered", false) {
private ListCell originalBttonCell = getButtonCell();
@Override
protected void invalidated() {
if(get()) {
setButtonCell(new ListCell() {
@Override
public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item.toString());
setAlignment(Pos.CENTER_RIGHT);
Insets old = getPadding();
setPadding(new Insets(old.getTop(), 0, old.getBottom(), 0));
}
}
});
}
else {
setButtonCell(originalBttonCell);
}
}
};
}
使用
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CustomComboBoxTest extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
VBox p = new VBox();
CustomComboBox box = new CustomComboBox<>(FXCollections.observableArrayList("Item 1", "Item 2", "Item 3"));
box.setValue("Item 2");
Button b = new Button("Change centered");
b.setOnAction( e -> {box.setCentered(!box.isCentered());});
p.getChildren().addAll(box, b);
Scene scene = new Scene(p);
primaryStage.setScene(scene);
primaryStage.setWidth(300);
primaryStage.setHeight(200);
primaryStage.show();
}
}