Is there any way I can display multiple components(like CheckBox, Label etc.) to a single cell of a Vaadin Grid? The Grid displays data populated dynamically by a GeneratedPropertyContainer.
Thanks in advance.
If you search the Vaadin directory you will find a few extensions, such as ComponentRenderer add-on which allow you to have such features in a somewhat painless way. Below you can see a code sample based on Vaadin v7.7.3 and v1.0.2 of the before-mentioned add-on. Please remember to update and recompile your widgetset.
public class GridWithMultiComponentRenderer extends VerticalLayout {
private static final String BUTTONS_ID = "buttons";
public GridWithMultiComponentRenderer() {
// basic grid setup
Grid grid = new Grid(new BeanItemContainer<>(Person.class));
grid.setSizeFull();
addComponent(grid);
// add the decorator
ComponentGridDecorator<Person> gridDecorator = new ComponentGridDecorator<>(grid, Person.class);
// generate the column which will display the components
gridDecorator.addComponentColumn(BUTTONS_ID, person -> new HorizontalLayout(
new Button("Get name", event -> Notification.show(person.getName())),
new Button("Get surname", event -> Notification.show(person.getSurname())),
new Button("Get age", event -> Notification.show(String.valueOf(person.getAge())))
));
// set column order
grid.setColumns("name", "surname", "age", BUTTONS_ID);
// add some dummy data
Random random = new Random();
for (int i = 0; i < 10; i++) {
gridDecorator.add(new Person("Name " + i, "Surname " + i, random.nextInt(99) + 1));
}
}
// POJO for simple binding
public static class Person {
private String name;
private String surname;
private int age;
public Person(String name, String surname, int age) {
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
Result:
Related
I am new to DynamoDB and wanted to know how can we query on a table in DynamoDB by using ONLY partition key in JAVA
I have table called "ervive-pdi-data-invalid-qa" and it's Schema is :
partition key is "SubmissionId"
Sort key is "Id".
City (Attribute)
Errors (Attribute)
The table looks like this:
Table
I want to retrieve the sort key value and remaining attributes data by using Partition key using (software.amazon.awssdk) new version of AWS SDK DynamoDB classes.
is it possible to get it? If so, can any one post the answers?
Have tried this:
DynamoDbClient ddb =
DynamoDbClient.builder().region(Region.US_EAST_1).build();
DynamoDbEnhancedClient enhancedClient =
DynamoDbEnhancedClient.builder()
.dynamoDbClient(ddb)
.build();
//Define table
DynamoDbTable<ErvivePdiDataInvalidQa> table =
enhancedClient.table("ervive-pdi-data-invalid-qa",
TableSchema.fromBean(ErvivePdiDataInvalidQa.class));
Key key = Key.builder().partitionValue(2023).build();
ErvivePdiDataInvalidQa result = table.getItem(r->r.key(key));
System.out.println("The record id is "+result.getId());
ErvivePdiDataInvalidQa table class is in below comment*
and it is returning "The provided key element does not match the schema (Service: DynamoDb, Status Code: 400, Request ID: PE1MKPMQ9MLT51OLJQVDCURQGBVV4KQNSO5AEMVJF66Q9ASUAAJG, Extended Request ID: null)"
Query you need is documented in one of the examples of AWS Dynamodb Query API for Java.
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
.withRegion(Regions.US_WEST_2).build();
DynamoDB dynamoDB = new DynamoDB(client);
Table table = dynamoDB.getTable("ervive-pdi-data-invalid-qa");
QuerySpec spec = new QuerySpec()
.withKeyConditionExpression("SubmissionId = :v_id")
.withValueMap(new ValueMap()
.withInt(":v_id", 2146));
ItemCollection<QueryOutcome> items = table.query(spec);
Iterator<Item> iterator = items.iterator();
Item item = null;
while (iterator.hasNext()) {
item = iterator.next();
System.out.println(item.toJSONPretty());
}
A single Query operation can retrieve a maximum of 1 MB of data, see documentation
I have been working with Padma on this issue. We first tried A. Khan's code but could not get passed authentication with v1. Instead we got "WARNING: Your profile name includes a 'profile ' prefix. This is considered part of the profile name in the Java SDK, so you will need to include this prefix in your profile name when you reference this profile from your Java code."
ultimately it could not get the credentials. Our credentials assume IAM roles in .aws/config-i2 file. It works fine in v2 but not v1.
So then we tried v2 of the SDK and have no problems with connecting but we get NULL returned on trying to fetch all records from the table.
In all of the below attempts using v2 of SDK, table data returns NULL
We created this table class
package data;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;
#DynamoDbBean
public class ErvivePdiDataInvalidQa {
private int submissionId;
private String id;
private String address1;
private String city;
private String dateOfBirth;
private String errors;
private String firstName;
private String firstNameNormalized;
private String gender;
private String lastName;
private String lastNameNormalized;
private String middleNameInitial;
private String postalCode;
private String rowNumber;
private String state;
private String submissionType;
#DynamoDbPartitionKey
public int getSubmissionId() {
return submissionId;
}
public void setSubmissionId(int submissionId) {
this.submissionId = submissionId;
}
#DynamoDbSortKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String Address1) {
this.address1 = Address1;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getErrors() {
return errors;
}
public void setErrors(String errors) {
this.errors = errors;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstNameNormalized() {
return firstNameNormalized;
}
public void setFirstNameNormalized(String firstNameNormalized) {
this.firstNameNormalized = firstNameNormalized;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastNameNormalized() {
return lastNameNormalized;
}
public void setLastNameNormalized(String lastNameNormalized) {
this.lastNameNormalized = lastNameNormalized;
}
public String getMiddleNameInitial() {
return middleNameInitial;
}
public void setMiddleNameInitial(String middleNameInitial) {
this.middleNameInitial = middleNameInitial;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getRowNumber() {
return rowNumber;
}
public void setRowNumber(String rowNumber) {
this.rowNumber = rowNumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getSubmissionType() {
return submissionType;
}
public void setSubmissionType(String submissionType) {
this.submissionType = submissionType;
}
}
DynamoDB code to get all records
//Connection
DynamoDbClient ddb = DynamoDbClient.builder().build();
DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
.dynamoDbClient(ddb)
.build();
//Define table
DynamoDbTable<ErvivePdiDataInvalidQa> table = enhancedClient.table("ervive-pdi-data-invalid-qa", TableSchema.fromBean(ErvivePdiDataInvalidQa.class));
//Get All Items from table - RETURNING NULL
Iterator<ErvivePdiDataInvalidQa> results = table.scan().items().iterator();
while (results.hasNext()) {
ErvivePdiDataInvalidQa rec = results.next();
System.out.println("The record id is "+rec.getId());
}
Also tried:
DynamoDB code to filter by SubmissionID
AttributeValue attr = AttributeValue.builder()
.n("1175")
.build();
// Get only Open items in the Work table
Map<String, AttributeValue> myMap = new HashMap<>();
myMap.put(":val1", attr);
Map<String, String> myExMap = new HashMap<>();
myExMap.put("#sid", "SubmissionId");
// Set the Expression so only Closed items are queried from the Work table
Expression expression = Expression.builder()
.expressionValues(myMap)
.expressionNames(myExMap)
.expression("#sid = :val1")
.build();
ScanEnhancedRequest enhancedRequest = ScanEnhancedRequest.builder()
.filterExpression(expression)
.limit(15)
.build();
// Get items in the Record table and write out the ID value
Iterator<ErvivePdiDataInvalidQa> results = table.scan(enhancedRequest).items().iterator();
while (results.hasNext()) {
ErvivePdiDataInvalidQa record = results.next();
System.out.println("The record id is " + record.getId());
}
I have a particular TreeTableView that displays a hierarchical tree of mixed types. These types do not necessarily have overlapping columns and as such the columns for some rows will be empty. As an example, consider the following classes:
public class Person {
private final StringProperty nameProperty;
private final StringProperty surnameProperty;
public Person() {
this.nameProperty = new SimpleStringProperty();
this.surnameProperty = new SimpleStringProperty();
}
public StringProperty nameProperty() {
return this.nameProperty;
}
public void setName(String value) {
this.nameProperty.set(value);
}
public String getName() {
return this.nameProperty.get();
}
public StringProperty surnameProperty() {
return this.surnameProperty;
}
public void setSurname(String value) {
this.surnameProperty.set(value);
}
public String getSurname() {
return this.surnameProperty.get();
}
}
public class Dog {
private final StringProperty nameProperty;
private final IntegerProperty ageProperty;
private final StringProperty breedProperty;
public Dog() {
this.nameProperty = new SimpleStringProperty();
this.ageProperty = new SimpleIntegerProperty();
this.breedProperty = new SimpleStringProperty();
}
public StringProperty nameProperty() {
return this.nameProperty;
}
public void setName(String value) {
this.nameProperty.set(value);
}
public String getName() {
return this.nameProperty.get();
}
public IntegerProperty ageProperty() {
return this.ageProperty;
}
public void setAge(int value) {
this.ageProperty.setValue(value);
}
public int getAge() {
return this.ageProperty.get();
}
public StringProperty breedProperty() {
return this.breedProperty;
}
public void setBreed(String breed) {
this.breedProperty.set(breed);
}
public String getBreed() {
return this.breedProperty.get();
}
}
If I construct the TreeTableView as follows:
TreeTableView<Object> treeTableView = new TreeTableView<>();
treeTableView.setEditable(true);
List<TreeTableColumn<Object, ?>> columns = treeTableView.getColumns();
TreeTableColumn<Object, String> nameColumn = new TreeTableColumn<>("Name");
nameColumn.setCellValueFactory(new TreeItemPropertyValueFactory<>("name"));
nameColumn.setCellFactory(TextFieldTreeTableCell.forTreeTableColumn());
columns.add(nameColumn);
TreeTableColumn<Object, String> surnameColumn = new TreeTableColumn<>("Surname");
surnameColumn.setCellFactory(TextFieldTreeTableCell.forTreeTableColumn());
surnameColumn.setCellValueFactory(new TreeItemPropertyValueFactory<>("surname"));
columns.add(surnameColumn);
TreeTableColumn<Object, Integer> ageColumn = new TreeTableColumn<>("Age");
ageColumn.setCellFactory(TextFieldTreeTableCell.forTreeTableColumn(new IntegerStringConverter()));
ageColumn.setCellValueFactory(new TreeItemPropertyValueFactory<>("age"));
columns.add(ageColumn);
TreeTableColumn<Object, String> breedColumn = new TreeTableColumn<>("Breed");
breedColumn.setCellFactory(TextFieldTreeTableCell.forTreeTableColumn());
breedColumn.setCellValueFactory(new TreeItemPropertyValueFactory<>("breed"));
columns.add(breedColumn);
TreeItem<Object> rootItem = new TreeItem<>();
treeTableView.setRoot(rootItem);
treeTableView.setShowRoot(false);
List<TreeItem<Object>> rootChildren = rootItem.getChildren();
Person john = new Person();
john.setName("John");
john.setSurname("Denver");
TreeItem<Object> johnTreeItem = new TreeItem<>(john);
rootChildren.add(johnTreeItem);
List<TreeItem<Object>> johnChildren = johnTreeItem.getChildren();
Dog charlie = new Dog();
charlie.setName("Charlie");
charlie.setAge(4);
charlie.setBreed("Labrador");
TreeItem<Object> charlieTreeItem = new TreeItem<>(charlie);
johnChildren.add(charlieTreeItem);
Dog daisy = new Dog();
daisy.setName("Daisy");
daisy.setAge(7);
daisy.setBreed("Bulldog");
TreeItem<Object> daisyTreeItem = new TreeItem<>(daisy);
johnChildren.add(daisyTreeItem);
I will get a TreeTableView that looks like:
The Age and Breed columns are empty for the TreeItems that contains Person objects. However, nothing stops me from editing Age or Breed cell for the top-most Person row. Setting a value in one of those cells doesn't change the Person object, but the value still hangs around there like it is committed.
Is there any way to prevent this from happening? I know that I could check for nulls in a custom TreeTableCell subclass and prevent the editing from kicking off in the startEdit() method. However, there are circumstances where a null-value is valid and preventing editing by checking nulls is not a feasible solution for all situations. Also, creating a custom TreeTableCell subclass for every datatype and corresponding columns is painful. It would have been nice if TreeItemPropertyValueFactory could provide for a way to abort the edit when no value is present for a particular cell.
Ok, I scraped together something by looking at the TreeItemPropertyValueFactory class itself for inspiration. This gives me the desired functionality, although I'm not sure if it is 100% correct or what the implications are of using it.
It basically comes down to installing a new cell-factory that checks if the cell-value-factory is of type TreeItemPropertyValueFactory. If it is the case, a new cell-factory is installed that delegates to the original but adds listeners for the table-row and tree-item properties. When the TreeItem changes, we get the row-data and see if we can access the desired property (via a PropertyReference that is cached for performance). If we can't (and we get the two exceptions) we assume that the property cannot be accessed and we set the cell's editable-property to false.
public <S, T> void disableUnavailableCells(TreeTableColumn<S, T> treeTableColumn) {
Callback<TreeTableColumn<S, T>, TreeTableCell<S, T>> cellFactory = treeTableColumn.getCellFactory();
Callback<CellDataFeatures<S, T>, ObservableValue<T>> cellValueFactory = treeTableColumn.getCellValueFactory();
if (cellValueFactory instanceof TreeItemPropertyValueFactory) {
TreeItemPropertyValueFactory<S, T> valueFactory = (TreeItemPropertyValueFactory<S, T>)cellValueFactory;
String property = valueFactory.getProperty();
Map<Class<?>, PropertyReference<T>> propertyRefCache = new HashMap<>();
treeTableColumn.setCellFactory(column -> {
TreeTableCell<S, T> cell = cellFactory.call(column);
cell.tableRowProperty().addListener((o1, oldRow, newRow) -> {
if (newRow != null) {
newRow.treeItemProperty().addListener((o2, oldTreeItem, newTreeItem) -> {
if (newTreeItem != null) {
S rowData = newTreeItem.getValue();
if (rowData != null) {
Class<?> rowType = rowData.getClass();
PropertyReference<T> reference = propertyRefCache.get(rowType);
if (reference == null) {
reference = new PropertyReference<>(rowType, property);
propertyRefCache.put(rowType, reference);
}
try {
reference.getProperty(rowData);
} catch (IllegalStateException e1) {
try {
reference.get(rowData);
} catch (IllegalStateException e2) {
cell.setEditable(false);
}
}
}
}
});
}
});
return cell;
});
}
}
For the example listed in the question, you can call it after you created all your columns as:
...
columns.forEach(this::disableUnavailableCells);
TreeItem<Object> rootItem = new TreeItem<>();
treeTableView.setRoot(rootItem);
treeTableView.setShowRoot(false);
...
You'll see that cells for the Age and Breed columns are now uneditable for Person entries whereas cells for the Surname column is now uneditable for Dog entries, which is what we want. Cells for the common Name column is editable for all entries as this is a common property among Person and Dog objects.
//Database is Sucessfully Connected
I am trying to Create a table in which I want to display the contents of my 'student' table in tableView of Javafx but I could not get the desired output.
ObservableList<Student> list = FXCollections.observableArrayList();
#FXML
//Initializes the controller class.
#Override
public void initialize(URL url, ResourceBundle rb)
{
// TODO
initCol();
loadTable();
}
//A view Table has been made with fx:id-table
//Variable name for 2 columns are 'fx:id-rollnoColand' & 'fx:id-nameCol'
#FXML
private TableView<Student> table;
#FXML
private TableColumn<Student,String> rollnoCol;
#FXML
private TableColumn<Student,String> nameCol;
private void initCol()
{
rollnoCol.setCellValueFactory(new PropertyValueFactory<>("s_rollno"));
nameCol.setCellValueFactory(new PropertyValueFactory<>("s_name"));
}
//Name of the Table is 'student' with Columns 'rollno' and 'name'
private void loadTable()
{
String selectAll = "select * from student";
try
{
Statement stmt = connectdb.createStatement();
ResultSet rs = stmt.executeQuery(selectAll);
while(rs.next())
{
String getrollno = rs.getString("rollno");
String getname = rs.getString("name");
list.add(new Student(getrollno,getname));
}
}
catch(SQLException exp)
{
System.out.println(exp);
}
table.getItems().setAll(list);
}
public static class Student
{
private final String s_rollno;
private final String s_name;
Student(String rollno,String name)
{
this.s_rollno = rollno;
this.s_name = name;
}
}
PropertyValueFactory works with getters or property methods. In your case you need to add getters for your properties in the Student class to enable PropertyValueFactory to retrieve the values:
public static class Student {
private final String s_rollno;
private final String s_name;
Student(String rollno, String name) {
this.s_rollno = rollno;
this.s_name = name;
}
public String getS_rollno() {
return s_rollno;
}
public String getS_name() {
return s_name;
}
}
I had this problem before,and it has many reason.First ,you may remove final keyword from your model,because your variables are changing.Second, TableView shows empty cells because you make your variables private in class Student and you can not access them from init method in parent class.So you need add getter and setter methods for access to these variables.
public static class Student
{
private String s_rollno;
private String s_name;
Student(String rollno,String name)
{
this.s_rollno = rollno;
this.s_name = name;
}
public String getS_rollno() {
return s_rollno;
}
public void setS_rollno(String s_rollno) {
this.s_rollno = s_rollno;
}
public String getS_name() {
return s_name;
}
public void setS_name(String s_name) {
this.s_name = s_name;
}
}
I am making a system for a school project , and one part of it is a TableView that is populated with rows using my own data class InventoryData that has properties correspondent to the table columns. I would like to make cells in some columns editable using a TextField, so that when an edit is committed, it will update the InventoryData object's relevant property.
I tried setting TextFieldTableCell.forTableColumn() as the cell factory of the columns. Although, now after committing the edit, the text in the cell will change, I don't think it is changing the property in the InventoryData object. The reason why I think that, is because when I try to edit that cell again ( after already being edited once), the TextField shows the former value ( before the first edit).
Did I do something wrong , or is that normal behavior and I have to implement the commits myself?
Here's the code for InventoryData :
package UILayer.TableData;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import ModelLayer.Product;
public class InventoryData {
// From Product
private Product productObj;
private SimpleIntegerProperty id;
private SimpleStringProperty name;
// Constructor - converts Product obj into InventoryData
public InventoryData(Product product)
{
this.productObj = product;
this.id = new SimpleIntegerProperty(product.getId());
this.name = new SimpleStringProperty(product.getName())
}
// GET & SET
public Product getProduct()
{
return productObj;
}
public int getId() {
return id.get();
}
public void setId(int id) {
this.id.set(id);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
productObj.setName(name);
System.out.println(productObj.getName());
}
}
You need your InventoryData class to use the JavaFX Properties pattern. Specifically it needs property-type accessor methods in order to retrieve the property in the table cells. Without this, the cell value factory just calls the standard getName() or getId() method, and wraps the result in a ReadOnlyStringWrapper (or ReadOnlyIntegerWrapper): the table cell cannot change the values of those wrappers (since they are read only).
public class InventoryData {
// From Product
private Product productObj;
private IntegerProperty id;
private StringProperty name;
// Constructor - converts Product obj into InventoryData
public InventoryData(Product product)
{
this.productObj = product;
this.id = new SimpleIntegerProperty(product.getId());
this.name = new SimpleStringProperty(product.getName())
this.name.addListener((obs, oldName, newName) ->
productObj.setName(newName));
}
// GET & SET
public Product getProduct()
{
return productObj;
}
public IntegerProperty idProperty() {
return id ;
}
public final int getId() {
return idProperty().get();
}
public final void setId(int id) {
idProperty().set(id);
}
public StringProperty nameProperty() {
return name ;
}
public final String getName() {
return nameProperty().get();
}
public final void setName(String name) {
this.nameProperty().set(name);
// productObj.setName(name);
// System.out.println(productObj.getName());
}
}
I have tables with editable fields item,Description,Quantity,Unit price and Sub Total.
I am creating a cellFactory and Column Update like this:
TableColumn DescriptionCol = new TableColumn("Description");
EditableTableSupport.createEditingColumn(DescriptionCol,"description");
TableColumn QuantityCol = new TableColumn("Quantity");
EditableTableSupport.createEditingColumn(QuantityCol,"quantity");
TableColumn UnitPriceColumn = new TableColumn<>("Unit Price");
EditableTableSupport.createEditingColumn(UnitPriceColumn,"unitPrice");
TableColumn DiscountColumn = new TableColumn<>("Discount");
EditableTableSupport.createEditingColumn(DiscountColumn,"discount");
SubTotalColumn = new TableColumn<>("SubTotal");
EditableTableSupport.createColumn(SubTotalColumn,"subTotal");
TableColumn SubTotalColumn = new TableColumn<>("SubTotal");
EditableTableSupport.createColumn(SubTotalColumn,"subTotal");
DescriptionCol.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String> t) {
((DUMMY_PurchaseOrderLine) t.getTableView().getItems().get(t.getTablePosition().getRow())).setDescription(t.getNewValue());
}
});
QuantityCol.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String> t) {
((DUMMY_PurchaseOrderLine) t.getTableView().getItems().get(t.getTablePosition().getRow())).setQuantity(t.getNewValue());
}
});
UnitPriceColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String> t) {
((DUMMY_PurchaseOrderLine) t.getTableView().getItems().get(t.getTablePosition().getRow())).setUnitPrice(t.getNewValue());
}
});
DiscountColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<DUMMY_PurchaseOrderLine, String> t) {
((DUMMY_PurchaseOrderLine) t.getTableView().getItems().get(t.getTablePosition().getRow())).setDiscount(t.getNewValue());
}
});
public class EditableTableSupport {
public static void createEditingColumn(TableColumn Column ,String name){
Callback<TableColumn, TableCell> cellFactory = new Callback<TableColumn, TableCell>() {
#Override
public TableCell call(TableColumn p) {
return new EditingCell();
}
};
Column.setSortable(false);
Column.setCellValueFactory(new PropertyValueFactory<DUMMY_PurchaseOrderLine, String>(name));
Column.setCellFactory(cellFactory);
}
public static void createColumn(TableColumn Column, String name) {
Column.setSortable(false);
Column.setCellValueFactory(new PropertyValueFactory<DUMMY_PurchaseOrderLine, String>(name));
}}
Question:How to Update Subtotal Column When i updating Quantity Column or UnitPrice Column
Thank you..
public class DUMMY_PurchaseOrderLine {
private String name;
private String description;
private BigDecimal quantity;
private BigDecimal unitPrice;
private BigDecimal discount;
private BigDecimal subTotal;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getQuantity() {
return quantity;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public BigDecimal getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(BigDecimal unitPrice) {
this.unitPrice = unitPrice;
}
public BigDecimal getDiscount() {
return discount;
}
public void setDiscount(BigDecimal discount) {
this.discount = discount;
}
public BigDecimal getSubTotal() {
return subTotal;
}
public void setSubTotal(BigDecimal subTotal) {
this.subTotal = subTotal;
}
public DUMMY_PurchaseOrderLine(String name, BigDecimal description, BigDecimal quantity,BigDecimal unitPrice,BigDecimal discount,BigDecimal subTotal) {
this.name = name;
this.description = description;
this.quantity = quantity;
this.unitPrice = unitPrice;
this.discount = discount;
this.subTotal = quantity.multiply(unitPrice).subtract(discount);
}
}
In your DUMMY_PurchaseOrderLine class create a read only property named subTotal and initialize it in the constructor via binding. The combination of the binding and the PropertyValueFactory you use to set the value for the SubTotalColumn will ensure that the correct subtotal is always reflected.
class DUMMY_PurchaseOrderLine {
private IntegerProperty quantity = new SimpleIntegerProperty(0);
private DoubleProperty unitPrice = new SimpleDoubleProperty(0);
private DoubleProperty discount = new SimpleDoubleProperty(0);
private ReadOnlyDoubleWrapper subTotal = new ReadOnlyDoubleWrapper(0);
DUMMY_PurchaseOrderLine() {
subTotal.bind(quantity.multiply(unitPrice).subtract(discount));
}
IntegerProperty quantityProperty() { return quantity; }
IntegerProperty unitPriceProperty() { return unitPrice; }
IntegerProperty discountProperty() { return discount; }
ReadOnlyDoubleProperty subTotalProperty() { return subTotal.getReadOnlyProperty(); }
}
Note the naming conventions used. Using the correct naming convention is key.
I'm assuming here that the subtotal is just the calculated value for a single row (specifically by quantity * unitPrice - discount), not a total of values calculated across multiple rows (which would be quite a difficult problem to solve with a TableView).
Update based on question edit
I see from your update that you are using BigDecimal and JavaFX doesn't have a corresponding BigDecimalProperty, so either you will need to create one (not trivial if you want it to be fully featured) or use one of the existing property types.
Your alternate to using properties is to use the low level binding api to calculate subtotals, but I'd advise using properties if you can.