Java 从TableView中的可编辑列动态填充ChoiceBox
基本上,问题的标题说明了一切。我在tableview中有一列字符串(称为Java 从TableView中的可编辑列动态填充ChoiceBox,java,tableview,javafx-8,Java,Tableview,Javafx 8,基本上,问题的标题说明了一切。我在tableview中有一列字符串(称为type)和一列相应的数字(称为size),每行代表一个对象CargoItem,该对象有两个属性type和size。 这两列都是可编辑的。该表视图与相应的CargoItem可观察列表相关联,称为cargoList ChoiceBox最初设置为可观察列表。我有一个连接到ChoiceBox的侦听器,因此它可以用相应的size属性更新TextField。此操作正常:如果在“大小”列的单元格中键入新值,则文本字段中的相应值将更新(一
type
)和一列相应的数字(称为size
),每行代表一个对象CargoItem
,该对象有两个属性type
和size
。
这两列都是可编辑的。该表视图与相应的CargoItem
可观察列表相关联,称为cargoList
ChoiceBox最初设置为可观察列表。我有一个连接到ChoiceBox的侦听器,因此它可以用相应的size属性更新TextField。此操作正常:如果在“大小”列的单元格中键入新值,则文本字段中的相应值将更新(一旦选择了ChoiceBox项)
此时,如果我编辑type
列中的单元格,则ChoiceBox中的项目不会更新。我有一个诊断按钮,它将验证可观察列表是否正确更新。我想我需要在type列的单元格中放置一个侦听器,但不确定如何放置
下面是一个简单的工作示例,包含4个文件:Table_test02.fxml、CargoItem.java、ControllerTest.java和TestApp.java
表\u test02.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane fx:id="root" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="252.0" prefWidth="232.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="so_question01.ControllerTest">
<children>
<TableView fx:id="cargoTable" editable="true" layoutX="9.0" layoutY="30.0" prefHeight="107.0" prefWidth="213.0">
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
<columns>
<TableColumn fx:id="cargoTableTypeCol" maxWidth="130.0" minWidth="60.0" prefWidth="75.0" sortable="false" text="Type" />
<TableColumn fx:id="cargoTableSizeCol" maxWidth="118.0" minWidth="60.0" prefWidth="67.0" sortable="false" text="Size" />
</columns>
</TableView>
<Label layoutX="10.0" layoutY="11.0" text="Cargo">
<font>
<Font name="System Bold" size="12.0" />
</font>
</Label>
<ChoiceBox fx:id="externalChoiceBox" layoutX="9.0" layoutY="162.0" prefHeight="25.0" prefWidth="99.0" />
<TextField fx:id="externalTextField" layoutX="123.0" layoutY="162.0" prefHeight="25.0" prefWidth="99.0" />
<Button fx:id="diagnosticButton" layoutX="83.0" layoutY="210.0" mnemonicParsing="false" text="Diagnostic" textFill="#862828">
<font>
<Font name="Arial Black" size="11.0" />
</font>
</Button>
<Label layoutX="10.0" layoutY="143.0" text="Type">
<font>
<Font name="System Bold" size="12.0" />
</font>
</Label>
<Label layoutX="123.0" layoutY="144.0" text="Size">
<font>
<Font name="System Bold" size="12.0" />
</font>
</Label>
</children>
</AnchorPane>
package so_question01;
import javafx.beans.property.*;
public class CargoItem {
private final StringProperty type;
private final FloatProperty size;
public CargoItem() {
this.type = new SimpleStringProperty("");
this.size = new SimpleFloatProperty(0f);
}
public CargoItem(String type, float size) {
this.type = new SimpleStringProperty(type);
this.size = new SimpleFloatProperty(size);
}
public void setType(String type) {
this.type.set(type);
}
public void setSize(float size) {
this.size.set(size);
}
public String getType() {
if (!(type.get().equals("") || type.get() == null )) {
return type.get();
}
return "";
}
public float getSize() {
return size.get();
}
public StringProperty typeProperty() {
return type;
}
public FloatProperty sizeProperty() {
return size;
}
public void clear() {
this.type.set("");
this.size.set(0);
}
@Override
public String toString() {
return type.get();
}
public String display() {
return "\nCARGO ITEM:"
+ "\n\ttype: " + type.get()
+ "\n\tsize: " + size.get();
}
}
package so_question01;
import java.text.DecimalFormat;
import javafx.collections.ListChangeListener.*;
import javafx.collections.ObservableList;
import javafx.collections.FXCollections;
import javafx.collections.*;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.beans.value.ObservableValue;
import javafx.util.StringConverter;
import javafx.beans.value.*;
public class ControllerTest {
ObservableList<CargoItem> cargoList = FXCollections.observableArrayList();
private TestApp mainApp; // Reference to the main application.
@FXML private ChoiceBox externalChoiceBox;
@FXML private TextField externalTextField;
@FXML private Button diagnosticButton;
@FXML private TableView<CargoItem> cargoTable;
@FXML private TableColumn<CargoItem, Float> cargoTableSizeCol;
@FXML private TableColumn<CargoItem, String> cargoTableTypeCol;
public ControllerTest() { }
@FXML
private void initialize() {
//*****DIAGNOSTIC ONLY*******************//
diagnosticButton.setOnAction(e->{
for(CargoItem c: cargoList){
System.out.print(c.display());
}
});
//does not work when changes made via table editing, but may be useful when new list loaded from file?
cargoList.addListener(new ListChangeListener< CargoItem>(){
public void onChanged(Change<? extends CargoItem> c){
// Do your changes here
System.out.println(c.getList());
}});
//**** test choicebox***//
StringConverter cargoItemConverter= new CargoItemStringConverter();
externalChoiceBox.setConverter(cargoItemConverter);
//***************** CARGO TABLE **************//
cargoTable.setEditable(true);
// Initialize the cargo table with the 2 columns.
cargoTableTypeCol.setCellFactory(TextFieldTableCell.forTableColumn());
cargoTableTypeCol.setCellValueFactory(new PropertyValueFactory<>("type"));
cargoTableSizeCol.setCellFactory(TextFieldTableCell.forTableColumn(new FloatIntegerStringConverter()));
cargoTableSizeCol.setCellValueFactory(new PropertyValueFactory<>("size"));
}
/**
* Is called by the main application to give a reference back to itself.
*
* @param mainApp
*/
public void setMainApp(TestApp mainApp) {
this.mainApp = mainApp;
cargoList.setAll(mainApp.getCargoData());
// Add observable list data to the table
cargoTable.setItems(cargoList);
cargoTable.getSelectionModel().setCellSelectionEnabled(true);
externalChoiceBox.setItems(cargoList);
//adds listener to choicebox selection, so size is rendered to text field
externalChoiceBox.getSelectionModel().selectedItemProperty().addListener(
new ChangeListener<CargoItem>() {
@Override public void changed(ObservableValue<? extends CargoItem> observableValue, CargoItem oldChoice, CargoItem newChoice) {
externalTextField.setText(new FloatIntegerStringConverter().toString(newChoice.getSize()));
}
});
}
}
//*******string converter classes, nothing to see here************//
class CargoItemStringConverter extends StringConverter<CargoItem>{
@Override
public String toString(CargoItem c){
return c.toString();
}
@Override
public CargoItem fromString(String type){
return null;
}
}
class FloatIntegerStringConverter extends StringConverter<Float>
{
DecimalFormat decimalFormat = new DecimalFormat("##,###,##0");
private Float returnVal;
@Override
public Float fromString(String value) {
if (value == null) {
return null;
}
value = value.trim();
String digits = value.replaceAll("[^0-9.]", ""); //gets rid of non-numerics
if (digits.length() < 1) {
return null;
}
try{ //avoids exception by converting invalid strings to zero (which should just be redundant due to regexp above)
returnVal= Float.valueOf(Math.round(Float.valueOf(digits)));//have to do this so the float value coresponds to the rounded value in table
} catch(NumberFormatException e) { returnVal= Float.valueOf(0); }
return returnVal;
}
@Override
public String toString(Float value) {
if (value == null) { // If the specified value is null, return a zero-length String
return "";
}
return decimalFormat.format(value)+" MT"; //truncated integer representation, unit metric tonnes
}
}
package so_question01;
import java.io.*;
import javafx.fxml.FXMLLoader;
import javafx.scene.layout.*;
import javafx.collections.ObservableList;
import javafx.collections.FXCollections;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class TestApp extends Application {
private Stage primaryStage;
private ObservableList<CargoItem> cargoData = FXCollections.observableArrayList();
public TestApp() {
// create some sample data
CargoItem cargoInstance0 = new CargoItem("Toxic waste", 5000f);
CargoItem cargoInstance1 = new CargoItem("Cement", 10000f);
CargoItem cargoInstance2 = new CargoItem("Wheat", 20000f);
cargoData.add(cargoInstance0);
cargoData.add(cargoInstance1);
cargoData.add(cargoInstance2);
}
/**
* Returns the data as observable lists of objects.
* @return
*/
public ObservableList<CargoItem> getCargoData() {return cargoData; } //called in the controller
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("**** TEST ****");
show();
}
/**
* Initializes the root layout.
*/
public void show() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(TestApp.class.getResource("Table_test02.fxml"));
AnchorPane root = (AnchorPane) loader.load();
// Give the controller access to the main app.
ControllerTest controller = loader.getController();
controller.setMainApp(this);
// Show the scene containing the root layout.
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) { System.out.println(e);}
}
/**
* Returns the main stage.
* @return
*/
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
Application.launch(TestApp.class, (java.lang.String[])null);
}
}
ControllerTest.java:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane fx:id="root" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="252.0" prefWidth="232.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="so_question01.ControllerTest">
<children>
<TableView fx:id="cargoTable" editable="true" layoutX="9.0" layoutY="30.0" prefHeight="107.0" prefWidth="213.0">
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
<columns>
<TableColumn fx:id="cargoTableTypeCol" maxWidth="130.0" minWidth="60.0" prefWidth="75.0" sortable="false" text="Type" />
<TableColumn fx:id="cargoTableSizeCol" maxWidth="118.0" minWidth="60.0" prefWidth="67.0" sortable="false" text="Size" />
</columns>
</TableView>
<Label layoutX="10.0" layoutY="11.0" text="Cargo">
<font>
<Font name="System Bold" size="12.0" />
</font>
</Label>
<ChoiceBox fx:id="externalChoiceBox" layoutX="9.0" layoutY="162.0" prefHeight="25.0" prefWidth="99.0" />
<TextField fx:id="externalTextField" layoutX="123.0" layoutY="162.0" prefHeight="25.0" prefWidth="99.0" />
<Button fx:id="diagnosticButton" layoutX="83.0" layoutY="210.0" mnemonicParsing="false" text="Diagnostic" textFill="#862828">
<font>
<Font name="Arial Black" size="11.0" />
</font>
</Button>
<Label layoutX="10.0" layoutY="143.0" text="Type">
<font>
<Font name="System Bold" size="12.0" />
</font>
</Label>
<Label layoutX="123.0" layoutY="144.0" text="Size">
<font>
<Font name="System Bold" size="12.0" />
</font>
</Label>
</children>
</AnchorPane>
package so_question01;
import javafx.beans.property.*;
public class CargoItem {
private final StringProperty type;
private final FloatProperty size;
public CargoItem() {
this.type = new SimpleStringProperty("");
this.size = new SimpleFloatProperty(0f);
}
public CargoItem(String type, float size) {
this.type = new SimpleStringProperty(type);
this.size = new SimpleFloatProperty(size);
}
public void setType(String type) {
this.type.set(type);
}
public void setSize(float size) {
this.size.set(size);
}
public String getType() {
if (!(type.get().equals("") || type.get() == null )) {
return type.get();
}
return "";
}
public float getSize() {
return size.get();
}
public StringProperty typeProperty() {
return type;
}
public FloatProperty sizeProperty() {
return size;
}
public void clear() {
this.type.set("");
this.size.set(0);
}
@Override
public String toString() {
return type.get();
}
public String display() {
return "\nCARGO ITEM:"
+ "\n\ttype: " + type.get()
+ "\n\tsize: " + size.get();
}
}
package so_question01;
import java.text.DecimalFormat;
import javafx.collections.ListChangeListener.*;
import javafx.collections.ObservableList;
import javafx.collections.FXCollections;
import javafx.collections.*;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.beans.value.ObservableValue;
import javafx.util.StringConverter;
import javafx.beans.value.*;
public class ControllerTest {
ObservableList<CargoItem> cargoList = FXCollections.observableArrayList();
private TestApp mainApp; // Reference to the main application.
@FXML private ChoiceBox externalChoiceBox;
@FXML private TextField externalTextField;
@FXML private Button diagnosticButton;
@FXML private TableView<CargoItem> cargoTable;
@FXML private TableColumn<CargoItem, Float> cargoTableSizeCol;
@FXML private TableColumn<CargoItem, String> cargoTableTypeCol;
public ControllerTest() { }
@FXML
private void initialize() {
//*****DIAGNOSTIC ONLY*******************//
diagnosticButton.setOnAction(e->{
for(CargoItem c: cargoList){
System.out.print(c.display());
}
});
//does not work when changes made via table editing, but may be useful when new list loaded from file?
cargoList.addListener(new ListChangeListener< CargoItem>(){
public void onChanged(Change<? extends CargoItem> c){
// Do your changes here
System.out.println(c.getList());
}});
//**** test choicebox***//
StringConverter cargoItemConverter= new CargoItemStringConverter();
externalChoiceBox.setConverter(cargoItemConverter);
//***************** CARGO TABLE **************//
cargoTable.setEditable(true);
// Initialize the cargo table with the 2 columns.
cargoTableTypeCol.setCellFactory(TextFieldTableCell.forTableColumn());
cargoTableTypeCol.setCellValueFactory(new PropertyValueFactory<>("type"));
cargoTableSizeCol.setCellFactory(TextFieldTableCell.forTableColumn(new FloatIntegerStringConverter()));
cargoTableSizeCol.setCellValueFactory(new PropertyValueFactory<>("size"));
}
/**
* Is called by the main application to give a reference back to itself.
*
* @param mainApp
*/
public void setMainApp(TestApp mainApp) {
this.mainApp = mainApp;
cargoList.setAll(mainApp.getCargoData());
// Add observable list data to the table
cargoTable.setItems(cargoList);
cargoTable.getSelectionModel().setCellSelectionEnabled(true);
externalChoiceBox.setItems(cargoList);
//adds listener to choicebox selection, so size is rendered to text field
externalChoiceBox.getSelectionModel().selectedItemProperty().addListener(
new ChangeListener<CargoItem>() {
@Override public void changed(ObservableValue<? extends CargoItem> observableValue, CargoItem oldChoice, CargoItem newChoice) {
externalTextField.setText(new FloatIntegerStringConverter().toString(newChoice.getSize()));
}
});
}
}
//*******string converter classes, nothing to see here************//
class CargoItemStringConverter extends StringConverter<CargoItem>{
@Override
public String toString(CargoItem c){
return c.toString();
}
@Override
public CargoItem fromString(String type){
return null;
}
}
class FloatIntegerStringConverter extends StringConverter<Float>
{
DecimalFormat decimalFormat = new DecimalFormat("##,###,##0");
private Float returnVal;
@Override
public Float fromString(String value) {
if (value == null) {
return null;
}
value = value.trim();
String digits = value.replaceAll("[^0-9.]", ""); //gets rid of non-numerics
if (digits.length() < 1) {
return null;
}
try{ //avoids exception by converting invalid strings to zero (which should just be redundant due to regexp above)
returnVal= Float.valueOf(Math.round(Float.valueOf(digits)));//have to do this so the float value coresponds to the rounded value in table
} catch(NumberFormatException e) { returnVal= Float.valueOf(0); }
return returnVal;
}
@Override
public String toString(Float value) {
if (value == null) { // If the specified value is null, return a zero-length String
return "";
}
return decimalFormat.format(value)+" MT"; //truncated integer representation, unit metric tonnes
}
}
package so_question01;
import java.io.*;
import javafx.fxml.FXMLLoader;
import javafx.scene.layout.*;
import javafx.collections.ObservableList;
import javafx.collections.FXCollections;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class TestApp extends Application {
private Stage primaryStage;
private ObservableList<CargoItem> cargoData = FXCollections.observableArrayList();
public TestApp() {
// create some sample data
CargoItem cargoInstance0 = new CargoItem("Toxic waste", 5000f);
CargoItem cargoInstance1 = new CargoItem("Cement", 10000f);
CargoItem cargoInstance2 = new CargoItem("Wheat", 20000f);
cargoData.add(cargoInstance0);
cargoData.add(cargoInstance1);
cargoData.add(cargoInstance2);
}
/**
* Returns the data as observable lists of objects.
* @return
*/
public ObservableList<CargoItem> getCargoData() {return cargoData; } //called in the controller
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("**** TEST ****");
show();
}
/**
* Initializes the root layout.
*/
public void show() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(TestApp.class.getResource("Table_test02.fxml"));
AnchorPane root = (AnchorPane) loader.load();
// Give the controller access to the main app.
ControllerTest controller = loader.getController();
controller.setMainApp(this);
// Show the scene containing the root layout.
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) { System.out.println(e);}
}
/**
* Returns the main stage.
* @return
*/
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
Application.launch(TestApp.class, (java.lang.String[])null);
}
}
package so\u question01;
导入java.text.DecimalFormat;
导入javafx.collections.ListChangeListener.*;
导入javafx.collections.ObservableList;
导入javafx.collections.FXCollections;
导入javafx.collections.*;
导入javafx.fxml.fxml;
导入javafx.scene.control.Button;
导入javafx.scene.control.ChoiceBox;
导入javafx.scene.control.TableColumn;
导入javafx.scene.control.TableView;
导入javafx.scene.control.TextField;
导入javafx.scene.control.cell.*;
导入javafx.scene.control.cell.PropertyValueFactory;
导入javafx.beans.value.observeValue;
导入javafx.util.StringConverter;
导入javafx.beans.value.*;
公共类控制器测试{
ObservableList cargoList=FXCollections.observableArrayList();
private TestApp mainApp;//对主应用程序的引用。
@FXML专用选择框外部选择框;
@FXML私有文本字段externalTextField;
@FXML专用按钮诊断按钮;
@FXML私有表查看货物表;
@FXML私有表列CAGOTABLESIZECOL;
@FXML私有表列CAGOTABLETYPECOL;
公共控制器测试(){}
@FXML
私有void初始化(){
//*****仅诊断*******************//
诊断按钮。设置操作(e->{
货物(c项:货物清单){
系统输出打印(c.display());
}
});
//通过表格编辑进行更改时不起作用,但从文件加载新列表时可能有用?
cargoList.addListener(新的ListChangeListener(){
public void onchange(Change假设我正确理解了问题,您需要使用以下命令初始化您的cargoList
:
并在列表中添加以下更改侦听器:
cargoList.addListener(new ListChangeListener< CargoItem>(){
public void onChanged(Change<? extends CargoItem> c){
// Do your changes here
System.out.println(c.getList());
externalChoiceBox.getItems().setAll(cargoList);
}});
cargoList.addListener(新的ListChangeListener(){
更改公众假期(更改谢谢James,但我想我已经达到了理解的极限——编译器说没有可观察的类,我找不到所需的库。还有什么我需要做的吗?只需添加导入:import javafx.beans.Observable;
好的,谢谢!这几乎可以,但如果我更改了n在类型栏中的项目,旧项目仍然在ChoiceBox列表中…即如果我将“水泥”更改为“棒棒糖”,ChoiceBox将更新为“有毒废物”、“棒棒糖”、“水泥”、“小麦”,但可观察列表是正确的(水泥被棒棒糖替换)——有什么想法吗?是的,这听起来像是我所指的那种ChoiceBox
bug。你可以吗(即使只是暂时)将其更改为一个组合框
,然后查看其行为是否与此相同?(另请参见更新以回答)谢谢James,尝试了您的建议,您完全正确--从现在起我将专门使用组合框!