java fx 文本输入,自定义组合框,在JavaFX中居中文本

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值