JavaFX Coloured Table Row - javafx

I have a Table which has a row factory attached to it to colour some of the rows. The issue is that the rows only change colour after you scroll the table up and down. What do I need to do to get the background colour to display when the table is initiated?
There is a video here: https://screencast-o-matic.com/watch/cFQYlEqPSv
ObservableList<SupplierProductOTIF> orderData = FXCollections.observableArrayList();
orderTable.setRowFactory(row -> new TableRow<SupplierProductOTIF>() {
#Override
public void updateItem(SupplierProductOTIF item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setStyle("");
} else {
if (item.isException()) {
//We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setStyle("-fx-background-color: rgba(255, 0, 0, .25);");
}
} else if (item.getQtyToOrder() > 0) {
//We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setStyle("-fx-background-color: rgba(0, 255, 0, .25);");
}
} else {
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setStyle("");
}
setStyle("");
}
}
}
});
orderTable.setItems(orderData);
for (SupplierProductOTIF product : supplier.getOtifSupplierData()) {
if(product.getQtyToOrder() > 0 || product.isException()) {
orderData.add(0, product);
} else {
orderData.add(product);
}
}
Edit: Here's the full code of my class
public class ReplenishmentPopupController extends ReportController implements Initializable {
private SupplierOTIF supplier;
private SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy");
#FXML
private TableView orderTable;
#FXML
private TableColumn productName;
#FXML
private TableColumn sku;
#FXML
private TableColumn currentStock;
#FXML
private TableColumn maxLeadTime;
#FXML
private TableColumn qtyToOrder;
#FXML
private TableColumn qtyOnOrder;
#FXML
private TableColumn nextOrderDate;
#FXML
private TableColumn<SupplierProductOTIF, LocalDate> stockUntilDate;
#FXML
private TableColumn daysStock;
#FXML
private TableColumn averageStockDailySales;
#FXML
private TableColumn daysOfStockToHold;
#FXML
private TableColumn daysOfStockToOrder;
#FXML
private TableColumn incost;
#FXML
private TableColumn supplierCost;
#FXML
private TableColumn orderCost;
#FXML
private TableColumn supplierPreference;
#FXML
private TableColumn productStatus;
#FXML
private TableColumn boxQty;
#FXML
private TableColumn minimumOrderQty;
#FXML
private TableColumn qtyRequired;
#FXML
private TableColumn rrs;
#FXML
private TableColumn rank;
#FXML
private Button raisePurchaseOrderButton;
#FXML
private Label supplierLabel;
#FXML
private Label orderValueLabel;
private ObservableList<SupplierProductOTIF> orderData = FXCollections.observableArrayList();
#Override
public void initialize(URL url, ResourceBundle rb) {
initOrderTable();
}
public void initOrderTable() {
orderTable.setEditable(true);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
sku.setCellValueFactory(new PropertyValueFactory("sku"));
sku.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
productName.setCellValueFactory(new PropertyValueFactory("name"));
productName.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.1));
currentStock.setCellValueFactory(new PropertyValueFactory("freeStock"));
currentStock.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
averageStockDailySales.setCellValueFactory(new PropertyValueFactory("averageForecastDailySales"));
averageStockDailySales.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
//averageStockDailySales.setVisible(false);
daysStock.setCellValueFactory(new PropertyValueFactory("daysStock"));
daysStock.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
stockUntilDate.setCellValueFactory(new PropertyValueFactory("stockUntilDate"));
stockUntilDate.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.1));
stockUntilDate.setCellFactory(tc -> new TableCell<SupplierProductOTIF, LocalDate>() {
#Override
protected void updateItem(LocalDate date, boolean empty) {
super.updateItem(date, empty);
if (empty || date == null) {
setText(null);
} else {
setText(formatter.format(date));
}
}
});
maxLeadTime.setCellValueFactory(new PropertyValueFactory("maxLeadTime"));
maxLeadTime.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
qtyToOrder.setCellValueFactory(new PropertyValueFactory("qtyToOrder"));
qtyToOrder.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.075));
qtyToOrder.setCellFactory(TextFieldTableCell.forTableColumn(new StringConverter<Integer>() {
#Override
public String toString(Integer object) {
return object.toString();
}
#Override
public Integer fromString(String string) {
return Integer.parseInt(string);
}
}));
qtyToOrder.setOnEditCommit(
new EventHandler<CellEditEvent<SupplierProductOTIF, Integer>>() {
#Override
public void handle(CellEditEvent<SupplierProductOTIF, Integer> t) {
((SupplierProductOTIF) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setQtyToOrder(t.getNewValue());
updatePurchaseOrderValue();
}
});
daysOfStockToHold.setCellValueFactory(new PropertyValueFactory("daysOfStockRequired"));
daysOfStockToHold.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
qtyOnOrder.setCellValueFactory(new PropertyValueFactory("qtyOutStanding"));
qtyOnOrder.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.075));
//qtyOnOrder.setVisible(false);
minimumOrderQty.setCellValueFactory(new PropertyValueFactory("minimumOrderQty"));
minimumOrderQty.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
//minimumOrderQty.setVisible(false);
boxQty.setCellValueFactory(new PropertyValueFactory("boxQty"));
boxQty.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
qtyRequired.setCellValueFactory(new PropertyValueFactory("qtyRequired"));
qtyRequired.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
daysOfStockToOrder.setCellValueFactory(new PropertyValueFactory("daysOfStockToOrder"));
daysOfStockToOrder.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
//daysOfStockToOrder.setVisible(false);
incost.setCellValueFactory(new PropertyValueFactory("incost"));
incost.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
//incost.setVisible(false);
supplierCost.setCellValueFactory(new PropertyValueFactory("supplierCost"));
supplierCost.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
supplierCost.setVisible(false);
orderCost.setCellValueFactory(new PropertyValueFactory("orderCost"));
orderCost.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
//orderCost.setVisible(false);
supplierPreference.setCellValueFactory(new PropertyValueFactory("supplierPreference"));
supplierPreference.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
supplierPreference.setVisible(false);
productStatus.setCellValueFactory(new PropertyValueFactory("productStatus"));
productStatus.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
rrs.setCellValueFactory(new PropertyValueFactory("rank"));
rrs.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
rank.setCellValueFactory(new PropertyValueFactory("productRanking"));
rank.prefWidthProperty().bind(orderTable.widthProperty().multiply(0.05));
orderTable.setRowFactory(row -> new TableRow<SupplierProductOTIF>() {
#Override
public void updateItem(SupplierProductOTIF item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setStyle("");
} else {
if (item.isException()) {
//We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setStyle("-fx-background-color: rgba(255, 0, 0, .25);");
}
} else if (item.getQtyToOrder() > 0) {
//We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setStyle("-fx-background-color: rgba(0, 255, 0, .25);");
}
} else if (item.getQtyToOrder() == 0 && item.getFreeStock() <= 0) {
//We apply now the changes in all the cells of the row
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setStyle("-fx-background-color: rgba(0, 0, 255, .25);");
}
} else {
for (int i = 0; i < getChildren().size(); i++) {
((Labeled) getChildren().get(i)).setStyle("");
}
setStyle("");
}
}
}
});
}
public SupplierOTIF getSupplier() {
return supplier;
}
public void setSupplier(SupplierOTIF supplier) {
this.supplier = supplier;
}
public void calculatePurchaseOrder() {
supplier.calculateNumberOfDaysStock();
supplier.calculateQTYToOrder();
for (SupplierProductOTIF product : supplier.getOtifSupplierData()) {
if (product.getSupplierPreference() == 1) {
if (product.getQtyToOrder() > 0 || product.isException()) {
orderData.add(0, product);
} else {
orderData.add(product);
}
}
}
orderTable.setItems(orderData);
}
public void updatePurchaseOrderValue() {
double totalValue = 0.0;
for (SupplierProductOTIF product : orderData) {
totalValue += (product.getQtyToOrder() * product.getSupplierCost());
}
orderValueLabel.setText("Order Value: £" + SalesHelper.round(new BigDecimal(totalValue), 2, BigDecimal.ROUND_HALF_UP));
}
#Override
public void loadAndShowData() throws Exception {
calculatePurchaseOrder();
updatePurchaseOrderValue();
}
}

Related

Javafx application (calculator) isn't working on other computers

I have made a calculator using javafx(I am a beginner). It worked fine on my computer. When I shared with my friend, only the stage was loaded like this...
Whereas, in computer...
[![This is it, a simple calculator][2]][2]
As a java programmer, this is my first project. It would be great, if you help me out with this...
Well, I have created this with Netbeans IDE, and there are three classes. Calculate.java(to calculate) , JavaFXApplication8.java(extends application) , and FXMLDocumentController.java(to control FXML file)
public class JavaFXApplication8 extends Application {
#Override
public void start(Stage stage) throws Exception {
stage.initStyle(StageStyle.UNIFIED);
stage.setMaxHeight(350);
stage.setMaxWidth(360);
stage.setResizable(false);
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
stage.setTitle("Calculator");
Scene scene = new Scene(root);
Image icon=new Image("Calculator-icon.png");
stage.getIcons().add(icon);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
public class FXMLDocumentController implements Initializable {
public static String a="";
private void SetLabel(ActionEvent event) {
result.setText(a);
}
#FXML
private void OnePressed(ActionEvent event) {
a=a.concat("1");
result.setText(a);
}
#FXML
private void TwoPressed(ActionEvent event) {
a=a.concat("2");
result.setText(a);
}
#FXML
private void ThreePressed(ActionEvent event) {
a=a.concat("3");
result.setText(a);
}
#FXML
private void FourPressed(ActionEvent event) {
a=a.concat("4");
result.setText(a);
}
#FXML
private void FivePressed(ActionEvent event) {
a=a.concat("5");
result.setText(a);
}
#FXML
private void SixPressed(ActionEvent event) {
a=a.concat("6");
result.setText(a);
}
#FXML
private void SevenPressed(ActionEvent event) {
a=a.concat("7");
result.setText(a);
}
#FXML
private void EightPressed(ActionEvent event) {
a=a.concat("8");
result.setText(a);
}
#FXML
private void NinePressed(ActionEvent event) {
a=a.concat("9");
result.setText(a);
}
#FXML
private void ZeroPressed(ActionEvent event) {
a=a.concat("0");
result.setText(a);
}
#FXML
private void PointPressed(ActionEvent event) {
a=a.concat(".");
result.setText(a);
}
#FXML
private void DelPressed(ActionEvent event) {
a=Calculate.Del(a);
result.setText(a);
}
#FXML
private void ACPressed(ActionEvent event) {
a="";
result.setText(a);
}
#FXML
private void AddPressed(ActionEvent event) {
a=a.concat("+");
result.setText(a);
}
#FXML
private void SubtractPressed(ActionEvent event) {
a=a.concat("-");
result.setText(a);
}
#FXML
private void MultiplyPressed(ActionEvent event) {
a=a.concat("*");
result.setText(a);
}
#FXML
private void DividePressed(ActionEvent event) {
a=a.concat("/");
result.setText(a);
}
#FXML
private void PercentPressed(ActionEvent event) {
if(a.contains("/")){
a=Calculate.divide(a);
float percent=Float.valueOf(a);
percent*=100;
result.setText(String.valueOf(percent).concat("%"));
}
else{
result.setText("Syntax error");
}
}
#FXML
private void Result(ActionEvent event) {
try {
for (int i = 1; i < a.length(); i++) {
char ch=a.charAt(i);
switch (ch) {
case '+':
a=Calculate.add(a);
result.setText(" = "+a);
break;
case '-':
a=Calculate.subtract(a);
result.setText(" = "+a);
break;
case '*':
a=Calculate.multiply(a);
result.setText(" = "+a);
break;
case '/':
a=Calculate.divide(a);
result.setText(" = "+a);
break;
default:
break;
}
}
} catch (Exception e) {
result.setText("Syntax error");
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
private void SetLabel(MouseEvent event) {
}
}
public class Calculate {
public static String result;
public static String add(String s){
int d=0;
String fist="";
String secon="";
char ch='+';
for (int i = 0; i < s.length(); i++) {
char ch2=s.charAt(i);
if(ch==ch2){
fist=s.substring(0, i);
secon=s.substring(i+1, s.length());
}
}
float a=Float.valueOf(fist);
float b=Float.valueOf(secon);
float c=a+b;
if(String.valueOf(c).endsWith(".0")){
result=String.valueOf(c).substring(0, String.valueOf(c).length()-2);
}
else{
result=String.valueOf(c);
}
return result;
}
public static String subtract(String s){
String fist="";
String secon="";
char ch='-';
for (int i = 0; i < s.length(); i++) {
char ch2=s.charAt(i);
if(ch==ch2){
fist=s.substring(0, i);
secon=s.substring(i+1, s.length());
}
}
float a=Float.valueOf(fist);
float b=Float.valueOf(secon);
float c=a-b;
if(String.valueOf(c).endsWith(".0")){
result=String.valueOf(c).substring(0, String.valueOf(c).length()-2);
}
else{
result=String.valueOf(c);
}
return result;
}
public static String multiply(String s){
String fist="";
String secon="";
char ch='*';
for (int i = 0; i < s.length(); i++) {
char ch2=s.charAt(i);
if(ch==ch2){
fist=s.substring(0, i);
secon=s.substring(i+1, s.length());
}
}
float a=Float.valueOf(fist);
float b=Float.valueOf(secon);
float c=a*b;
if(String.valueOf(c).endsWith(".0")){
result=String.valueOf(c).substring(0, String.valueOf(c).length()-2);
}
else{
result=String.valueOf(c);
}
return result;
}
public static String divide(String s){
String fist="";
String secon="";
char ch='/';
for (int i = 0; i < s.length(); i++) {
char ch2=s.charAt(i);
if(ch==ch2){
fist=s.substring(0, i);
secon=s.substring(i+1, s.length());
}
}
float a=Float.valueOf(fist);
float b=Float.valueOf(secon);
float c=a/b;
if(String.valueOf(c).endsWith(".0")){
result=String.valueOf(c).substring(0, String.valueOf(c).length()-2);
}
else{
result=String.valueOf(c);
}
return result;
}
public static String Del(String s){
int len=s.length();
s=s.substring(0, len-1);
return s;
}
}
It became a little bit lengthy, but please go through it. It is damn easy for anyone who can attempt answering it.

Trying to include carousel with a timer in javafx

Trying to include carousel with a timer in javafx.
public class Controller {
#FXML
private ImageView imageslidder;
#FXML
private ImageView left;
#FXML
private ImageView right;
#FXML
private Circle picone;
#FXML
private Circle pictwo;
#FXML
private Circle picthree;
int imag_index = 0;
String images[] = new String []{"sample/one.jpg", "sample/two.jpg", "sample/three.jpg"};
void nextImage() {
switch (imag_index) {
case 0:
setStroke(picone);
resetStroke(pictwo);
resetStroke(picthree);
break;
case 1:
setStroke(pictwo);
resetStroke(picone);
resetStroke(picthree);
break;
case 2:
setStroke(picthree);
resetStroke(pictwo);
resetStroke(picone);
break;
default:
break;
}
imag_index++;
if (imag_index == images.length) ;
{
imag_index = 0;
}
try {
String imagpath = getClass().getResource(images[imag_index]).toURI().toString();
Image img = new Image(imagpath);
imageslidder.setImage(img);
} catch (Exception e) {
}
}
void prevImage() {
nextImage();
}
void setStroke(Circle indicator) {
indicator.setFill(Paint.valueOf("#03a9f4"));
indicator.setStroke(Paint.valueOf("#cddc39"));
indicator.setStrokeType(StrokeType.OUTSIDE);
indicator.setStrokeWidth(5);
}
void resetStroke(Circle indicator) {
indicator.setFill(Paint.valueOf("ffffff"));
indicator.setStroke(Paint.valueOf("#1e90ff"));
indicator.setStrokeType(StrokeType.INSIDE);
indicator.setStrokeWidth(1);
}
public void initializer(URL url, ResourceBundle rb)
{
}
}

How to eliminate the gray background of the tableview edit-cell

Problem
When you edit a table cell the row height usually becomes higher, which is unwanted behavior:
I managed to elimininate the height change with this css:
.text-field-table-cell {
-fx-padding: 0;
-fx-background-insets: 0.0;
}
.text-field-table-cell .text-field {
-fx-padding: 0;
-fx-background-insets: 0.0;
-fx-background-color:yellow;
-fx-border-width: 0;
}
But the cell is still not filled fully with the TextField. There's a gray background visible:
Question
Does anyone know how to eliminate the gray background of the edit-cell? Either by colorizing it or by removing it.
Code
Here's the full code if someone wants to test it:
InlineEditingTableViewCSS.java
public class InlineEditingTableViewCSS extends Application {
private final ObservableList<Data> data =
FXCollections.observableArrayList(
new Data(1.,5.),
new Data(2.,6.),
new Data(3.,7.),
new Data(4.,8.)
);
private TableView<Data> table;
#Override
public void start(Stage stage) {
// create edtiable table
table = new TableView<Data>();
table.setEditable(true);
// column 1 contains numbers
TableColumn<Data, Number> number1Col = new TableColumn<>("Number 1");
number1Col.setMinWidth(100);
number1Col.setCellValueFactory( cellData -> cellData.getValue().number1Property());
number1Col.setCellFactory( createNumberCellFactory());
// column 2 contains numbers
TableColumn<Data, Number> number2Col = new TableColumn<>("Number 2");
number2Col.setMinWidth(100);
number2Col.setCellValueFactory( cellData -> cellData.getValue().number2Property());
number2Col.setCellFactory( createNumberCellFactory());
// add columns & data to table
table.setItems(data);
table.getColumns().addAll( number1Col, number2Col);
// switch to edit mode on keypress
// this must be KeyEvent.KEY_PRESSED so that the key gets forwarded to the editing cell; it wouldn't be forwarded on KEY_RELEASED
table.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if( event.getCode() == KeyCode.ENTER) {
// event.consume(); // don't consume the event or else the values won't be updated;
return;
}
// switch to edit mode on keypress, but only if we aren't already in edit mode
if( table.getEditingCell() == null) {
if( event.getCode().isLetterKey() || event.getCode().isDigitKey()) {
TablePosition focusedCellPosition = table.getFocusModel().getFocusedCell();
table.edit(focusedCellPosition.getRow(), focusedCellPosition.getTableColumn());
}
}
}
});
table.addEventFilter(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if( event.getCode() == KeyCode.ENTER) {
table.getSelectionModel().selectBelowCell();
}
}
});
// single cell selection mode
table.getSelectionModel().setCellSelectionEnabled(true);
table.getSelectionModel().selectFirst();
// add nodes to stage
BorderPane root = new BorderPane();
root.setCenter(table);
Scene scene = new Scene( root, 800,600);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
stage.setScene(scene);
stage.show();
}
/**
* Number cell factory which converts strings to numbers and vice versa.
* #return
*/
private Callback<TableColumn<Data, Number>, TableCell<Data, Number>> createNumberCellFactory() {
Callback<TableColumn<Data, Number>, TableCell<Data, Number>> factory = TextFieldTableCell.forTableColumn( new StringConverter<Number>() {
#Override
public Number fromString(String string) {
return Double.parseDouble(string);
}
#Override
public String toString(Number object) {
return object.toString();
}
});
return factory;
}
/**
* Table data container
*/
public static class Data {
private final SimpleDoubleProperty number1;
private final SimpleDoubleProperty number2;
private Data( Double number1, Double number2) {
this.number1 = new SimpleDoubleProperty(number1);
this.number2 = new SimpleDoubleProperty(number2);
}
public final DoubleProperty number1Property() {
return this.number1;
}
public final double getNumber1() {
return this.number1Property().get();
}
public final void setNumber1(final double number1) {
this.number1Property().set(number1);
}
public final DoubleProperty number2Property() {
return this.number2;
}
public final double getNumber2() {
return this.number2Property().get();
}
public final void setNumber2(final double number2) {
this.number2Property().set(number2);
}
}
public static void main(String[] args) {
launch(args);
}
}
application.css
.text-field-table-cell {
-fx-padding: 0;
-fx-background-insets: 0.0;
}
.text-field-table-cell .text-field {
-fx-padding: 0;
-fx-background-insets: 0.0;
-fx-background-color:yellow;
-fx-border-width: 0;
}
Or is there a good mechanism to find out which CSS is currently being used by a node?
Thank you very much!
Does anyone know how to eliminate the gray background of the
edit-cell?
Set padding values for textfield:
.text-field-table-cell {
-fx-padding: 0;
-fx-background-insets: 0.0;
}
.text-field-table-cell .text-field {
-fx-padding: 3 0 3 0;
-fx-background-insets: 0.0;
-fx-background-color:yellow;
-fx-border-width: 0;
}

Why all rows in TableView have checkbox?

I creating project for my job. I need to use tableview and user need to check data going to database.
I was found how to add checkbox to TableView from this post
https://stackoverflow.com/a/7973514/3037869
This is working for me but my TableView now looking
How to fix this checkbox spam?
My code
public class ProductPSController extends BorderPane{
#FXML public TableColumn<ProductPS, String> produkt;
#FXML public TableColumn<ProductPS, String> symbol;
#FXML public TableColumn<ProductPS, String> atrybuty;
#FXML public TableColumn<ProductPS, Integer> id;
#FXML public TableColumn<ProductPS, Integer> stock;
#FXML public TableColumn<ProductPS, Integer> count;
#FXML public TableColumn<ProductPS, Integer> price;
#FXML public TableColumn<ProductPS, Boolean> checkbox;
#FXML public TableView <ProductPS> tab;
#FXML public BorderPane produkty;
public ObservableList<ProductPS> data = FXCollections.observableArrayList();
public ProductPSController()
{
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("product.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
id.prefWidthProperty().bind(tab.widthProperty().multiply(0.10));
stock.prefWidthProperty().bind(tab.widthProperty().multiply(0.10));
produkt.prefWidthProperty().bind(tab.widthProperty().multiply(0.20));
symbol.prefWidthProperty().bind(tab.widthProperty().multiply(0.10));
atrybuty.prefWidthProperty().bind(tab.widthProperty().multiply(0.30));
count.prefWidthProperty().bind(tab.widthProperty().multiply(0.10));
price.prefWidthProperty().bind(tab.widthProperty().multiply(0.10));
tab.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
setProduct();
}
public void setProduct()
{
id.setCellValueFactory(new PropertyValueFactory<ProductPS, Integer>("id"));
symbol.setCellValueFactory(new PropertyValueFactory<ProductPS, String>("symbol"));
stock.setCellValueFactory(new PropertyValueFactory<ProductPS, Integer>("id_stock"));
produkt.setCellValueFactory(new PropertyValueFactory<ProductPS, String>("product_name"));
atrybuty.setCellValueFactory(new PropertyValueFactory<ProductPS, String>("attributes"));
count.setCellValueFactory(new PropertyValueFactory<ProductPS, Integer>("count"));
Callback<TableColumn<ProductPS, Boolean>, TableCell<ProductPS, Boolean>> booleanCellFactory =
new Callback<TableColumn<ProductPS, Boolean>, TableCell<ProductPS, Boolean>>() {
#Override
public TableCell<ProductPS, Boolean> call(TableColumn<ProductPS, Boolean> p) {
return new BooleanCell();
}
};
price.setCellValueFactory(new PropertyValueFactory<ProductPS, Integer>("price"));
checkbox.setCellValueFactory(new PropertyValueFactory<ProductPS, Boolean>("checkbox"));
checkbox.setCellFactory(booleanCellFactory);
checkbox.setEditable(true);
try(Connection c = MysqlConnect.getConnection())
{
String SQL = "";
ResultSet rs = c.createStatement().executeQuery(SQL);
while(rs.next()){
data.add(new ProductPS(rs.getInt("id_product"),rs.getInt("id_stock_available"),rs.getString("name"),rs.getString("atrybuty"),rs.getInt("quantity"),rs.getFloat("price"),rs.getString("reference")));
}
c.close();
} catch (SQLException e) {
System.out.println(e.toString());
// TODO Auto-generated catch block
}
for(int i=0; i<data.size(); i++) {
if(i+1<data.size() && data.get(i).getAttributes().length()==0 && data.get(i).getId()==data.get(i+1).getId() ){data.remove(i);}
}
tab.setItems(data);
}
class BooleanCell extends TableCell<ProductPS, Boolean> {
private CheckBox checkBox;
public BooleanCell() {
checkBox = new CheckBox();
checkBox.setDisable(false);
checkBox.selectedProperty().addListener(new ChangeListener<Boolean> () {
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if(isEditing())
{
commitEdit(newValue == null ? false : newValue);
}
}
});
this.setGraphic(checkBox);
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
this.setEditable(true);
}
#Override
public void startEdit() {
super.startEdit();
if (isEmpty()) {
return;
}
checkBox.setDisable(false);
checkBox.requestFocus();
}
#Override
public void cancelEdit() {
super.cancelEdit();
checkBox.setDisable(true);
}
public void commitEdit(Boolean value) {
super.commitEdit(value);
checkBox.setDisable(true);
}
#Override
public void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (!isEmpty()) {
checkBox.setSelected(item);
}
}
}
}
Thx for help and say what i done bad.
In BooleanCell, you need to set the graphic to checkBox if the cell is not empty, and set it to null if it is empty.
Remove the line
this.setGraphic(checkBox);
from BooleanCell's constructor, and change updateItem(...) to:
#Override
public void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
checkBox.setSelected(item);
setGraphic(checkBox);
}
}

editable table in javafx

I'm trying to build a billing system in javafx, and I could build the table and everything. Now I want to change it, I want the table to be already editable, i.e the text fields in the table should be enabled to edit before onEditCommite. Also storing the data in the table is also giving a problem.
The code is given below. In the below code, the rows are being added and can be deleted. But I want to make it editable when the "new bill" button in clicked. Also any method to calculate the Price by multiplying the this.rate and this.qty.
public class abc extends Application {
private TableView<Billing> table = new TableView<Billing>();
private final ObservableList<Billing> data = FXCollections.observableArrayList();
final HBox hb = new HBox();
final HBox hb1=new HBox();
final HBox hb2= new HBox();
private IntegerProperty index = new SimpleIntegerProperty();
public static void main(String[] args) {
launch(args); }
// Stage Start method. Whole Stage.
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Billing");
stage.setWidth(550);
stage.setHeight(650);
final Label label = new Label("Billing Trial 2 ");
label.setFont(new Font("Comic Sans", 26));
//Call EditingCell and set true to make it editable
table.setEditable(true);
Callback<TableColumn, TableCell> cellFactory =
new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
return new EditingCell();
}
};
TableColumn srnoCol = new TableColumn("Sr. No. ");
srnoCol.setMinWidth(50);
srnoCol.setCellValueFactory(
new PropertyValueFactory<Billing, String>("srNo"));
srnoCol.setCellFactory(cellFactory);
TableColumn numCol = new TableColumn("Item Code ");
numCol.setMinWidth(50);
numCol.setCellValueFactory(
new PropertyValueFactory<Billing, String>("itemCode"));
numCol.setCellFactory(cellFactory);
numCol.setOnEditCommit(
new EventHandler<CellEditEvent<Billing, String>>() {
#Override
public void handle(CellEditEvent<Billing, String> t) {
((Billing) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setItemCode(t.getNewValue());
}
}
);
TableColumn nameCol = new TableColumn("Item Name ");
nameCol.setMinWidth(100);
nameCol.setCellValueFactory(
new PropertyValueFactory<Billing, String>("itemName"));
nameCol.setCellFactory(cellFactory);
nameCol.setOnEditCommit(
new EventHandler<CellEditEvent<Billing, String>>() {
#Override
public void handle(CellEditEvent<Billing, String> t) {
((Billing) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setItemName(t.getNewValue());
}
}
);
TableColumn qtyCol = new TableColumn("Qty ");
qtyCol.setMinWidth(100);
qtyCol.setCellValueFactory(
new PropertyValueFactory<Billing, String>("itemQty"));
qtyCol.setCellFactory(cellFactory);
qtyCol.setOnEditCommit(
new EventHandler<CellEditEvent<Billing, String>>() {
#Override
public void handle(CellEditEvent<Billing, String> t) {
((Billing) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setItemQty(t.getNewValue());
}
}
);
TableColumn rateCol = new TableColumn("Item Rate ");
rateCol.setMinWidth(50);
rateCol.setCellValueFactory(
new PropertyValueFactory<Billing, String>("itemRate"));
rateCol.setCellFactory(cellFactory);
rateCol.setOnEditCommit(
new EventHandler<CellEditEvent<Billing, String>>() {
#Override
public void handle(CellEditEvent<Billing, String> t) {
((Billing) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setItemRate(t.getNewValue());
}
}
);
TableColumn priceCol = new TableColumn("Item Price ");
priceCol.setMinWidth(50);
priceCol.setCellValueFactory(
new PropertyValueFactory<Billing, String>("itemPrice"));
priceCol.setCellFactory(cellFactory);
priceCol.setOnEditCommit(
new EventHandler<CellEditEvent<Billing, String>>() {
#Override
public void handle(CellEditEvent<Billing, String> t) {
((Billing) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setItemPrice(t.getNewValue());
}
}
);
table.setItems(data);
//indexing of elements for deleting function.
table.getSelectionModel().selectedItemProperty().addListener(newChangeListener<Object>() {
#Override
public void changed(ObservableValue<?>observable, Object oldvalue, Object newValue){
index.set(data.indexOf(newValue));
System.out.println("index: "+data.indexOf(newValue));
}
});
//Deleting
final Button deleteButton=new Button("Delete");
deleteButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent de){
int i = index.get();
if (i>-1){
data.remove(i);
table.getSelectionModel().clearSelection();
}
}
});
TableColumn amount = new TableColumn("Amount");
amount.getColumns().addAll(rateCol, priceCol);
table.setItems(data);
table.getColumns().addAll(srnoCol, numCol, nameCol, qtyCol, amount );
//add bill
final Button addButton = new Button("New Bill");
addButton.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent ae)
{
EditingCell ec = new EditingCell();
ec.getString();
ec.createTextField();
table.setEditable(true);
Callback<TableColumn, TableCell> cellFactory =
new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
return new EditingCell();
}
};
ec.startEdit();
ec.cancelEdit();
data.add(new Billing(null,null,null,null,null,null));
}
});
hb.getChildren().addAll( addButton, deleteButton);
hb.setAlignment(Pos.BASELINE_LEFT);
hb.setSpacing(16);
final Label label2 = new Label();
label2.setAlignment(Pos.BASELINE_RIGHT);
final VBox vbox = new VBox();
vbox.setSpacing(15);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label,hb2, hb, table,hb1);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
//Class Billing
public static class Billing {
private final SimpleStringProperty itemSrNo;
private final SimpleStringProperty itemCode;
private final SimpleStringProperty itemName;
private final SimpleStringProperty itemQty;
private final SimpleStringProperty itemRate;
private final SimpleStringProperty itemPrice;
private Billing(String iSrNo, String iCode, String iName, String iQty, String iRate,String iPrice)
{
this.itemSrNo = new SimpleStringProperty(iSrNo);
this.itemCode = new SimpleStringProperty(iCode);
this.itemName = new SimpleStringProperty(iName);
this.itemPrice = new SimpleStringProperty(iPrice);
this.itemQty = new SimpleStringProperty(iQty);
this.itemRate = new SimpleStringProperty(iRate);
}
public String getItemSrNo() {
return itemSrNo.get();
}
public void setItemSrNo(String iSrNo) {
itemSrNo.set(iSrNo);
}
public String getItemCode() {
return itemCode.get();
}
public void setItemCode(String iCode) {
itemCode.set(iCode);
}
public String getItemName() {
return itemName.get();
}
public void setItemName(String iName) {
itemName.set(iName);
}
public String getItemQty() {
return itemQty.get();
}
public void setItemQty(String iQty) {
itemQty.set(iQty);
}
public String getItemPrice() {
return itemPrice.get();
}
public void setItemPrice(String iPrice) {
itemPrice.set(iPrice);
}
public String getItemRate() {
return itemRate.get();
}
public void setItemRate(String iRate) {
itemRate.set(iRate);
}
}
//CellEditing
public class EditingCell extends TableCell<Billing, String> {
private TextField textField;
public EditingCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
}
else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
}
else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(new ChangeListener<Boolean>(){
#Override
public void changed(ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) {
if (!arg2) {
commitEdit(textField.getText());
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
}
// calculation of Qty x Rate.
class Calculate {
public String sum(int iQty, int iRate)
{
int sum = iQty*iRate;
String s =""+sum;
return s;
}
}
Old question but here is what I think should work : Dont use setGraphic(null) in your cellFactory. Always set it to TextField. Also for the calculation part you can add listeners to your properties in the data model and perform calculation on any change of values for those properties.

Resources