【发布时间】:2015-04-22 19:29:20
【问题描述】:
如何将两个 Spinner 控件绑定到一个 TableView 中?根据下面的截图,我想做一些事情: colA = colB / 2 (and colB = colA x 2...) :
这里是用来暴露问题的sn-p(故意简单):
TestApp.java
public class TestApp extends Application {
@Override
public void start(Stage stage) throws Exception {
final TableView<MyBean> tableView = new TableView<>();
final TableColumn<MyBean, Integer> colA = new TableColumn<>("Col A");
final TableColumn<MyBean, Integer> colB = new TableColumn<>("Col B");
colA.setCellFactory(col -> new SpinnerCell<MyBean, Integer>());
colA.setCellValueFactory(new PropertyValueFactory<MyBean, Integer>("valA"));
colB.setCellFactory(col -> new SpinnerCell<MyBean, Integer>());
colB.setCellValueFactory(new PropertyValueFactory<MyBean, Integer>("valB"));
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
tableView.setItems(FXCollections.observableArrayList(new MyBean(1, 2)));
tableView.getColumns().addAll(colA, colB);
stage.setScene(new Scene(new VBox(tableView), 500, 300));
stage.show();
}
public static void main(String[] args) {
Application.launch();
}
}
SpinnerCell.java
public class SpinnerCell<S, T> extends TableCell<S, T> {
private Spinner<Integer> spinner;
private ObservableValue<T> ov;
public SpinnerCell() {
this.spinner = new Spinner<Integer>(0, 100, 1);
setAlignment(Pos.CENTER);
}
@Override
protected void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
setText(null);
setGraphic(this.spinner);
if(this.ov instanceof IntegerProperty) {
this.spinner.getValueFactory().valueProperty().unbindBidirectional(((IntegerProperty) this.ov).asObject());
}
this.ov = getTableColumn().getCellObservableValue(getIndex());
if(this.ov instanceof IntegerProperty) {
this.spinner.getValueFactory().valueProperty().bindBidirectional(((IntegerProperty) this.ov).asObject());
}
}
}
}
MyBean.java
public class MyBean {
private IntegerProperty valA, valB;
public MyBean(int valA, int valB) {
this.valA = new SimpleIntegerProperty(this, "valA", valA);
this.valB = new SimpleIntegerProperty(this, "valB", valB);
}
public IntegerProperty valAProperty() {
return this.valA;
}
public void setValA(int valA) {
this.valA.set(valA);
}
public int getValA() {
return valA.get();
}
public IntegerProperty valBProperty() {
return this.valB;
}
public void setValB(int valB) {
this.valB.set(valB);
}
public int getValB() {
return valB.get();
}
}
【问题讨论】:
标签: java javafx spinner tableview javafx-8