JavaFX FXML Show Updated TableView - javafx

I'm having issues showing new additions to a class in a TableView for my JavaFX/FXML program. I've looked at countless tutorials but the missing piece still escapes me.
I had some errors that got fixed here: JavaFX Adding Rows to TableView on Different Page
And then found a new tutorial to sort of follow that explained things a bit better than the first one I was following (their app is a bit different than what I have to do) here: http://code.makery.ch/library/javafx-8-tutorial/part2/
I have an output printing the name field out to the console just to make sure it is pulling the right values from the add form. I also changed the way I navigated between Add Part and the Main window (nothing else works right now). I feel so silly asking this, but Java is the one language I haven't been able to wrap my head around.
Any ideas on why it isn't updating are greatly appreciated.
IMS.java
package ims;
import java.io.IOException;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
/**
*
* #author chelseacamper
*/
public class IMS extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private ObservableList<Part> partData = FXCollections.observableArrayList();
public IMS() {
partData.add(new Part("Part A", 3, 4.00, 1, 5));
partData.add(new Part("Part B", 2, 14.00, 1, 15));
}
public ObservableList<Part> getPartData(){
return partData;
}
#Override
public void start(Stage stage) throws Exception {
// Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
Parent root = (Parent) loader.load();
FXMLDocumentController ctrl = loader.getController();
ctrl.setMainApp(this);
Scene scene = new Scene(root);
scene.getStylesheets().add("style.css");
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
FXMLDocumentController.java
package ims;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
/**
*
* #author chelseacamper
*/
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
#FXML
private TableView<Part> partTable;
#FXML
private TableColumn<Part, Integer> partIDColumn;
#FXML
private TableColumn<Part, String> nameColumn;
#FXML
private TableColumn<Part, Integer> inventoryColumn;
#FXML
private TableColumn<Part, Double> priceColumn;
private IMS mainApp;
public FXMLDocumentController(){
}
#FXML
private void addPart(ActionEvent event) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("addPart.fxml"));
Parent add_part_parent = (Parent) loader.load();
Stage stage = new Stage();
stage.setScene(new Scene(add_part_parent));
stage.show();
}
#FXML
private void modifyPart(ActionEvent event) throws IOException {
Parent modify_part_parent = FXMLLoader.load(getClass().getResource("modifyPart.fxml"));
Scene modify_part_scene = new Scene(modify_part_parent);
modify_part_scene.getStylesheets().add("style.css");
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(modify_part_scene);
app_stage.show();
}
#FXML
private void addProduct(ActionEvent event) throws IOException {
Parent add_product_parent = FXMLLoader.load(getClass().getResource("addProduct.fxml"));
Scene add_product_scene = new Scene(add_product_parent);
add_product_scene.getStylesheets().add("style.css");
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(add_product_scene);
app_stage.show();
}
#FXML
private void modifyProduct(ActionEvent event) throws IOException {
Parent modify_product_parent = FXMLLoader.load(getClass().getResource("modifyProduct.fxml"));
Scene modify_product_scene = new Scene(modify_product_parent);
modify_product_scene.getStylesheets().add("style.css");
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(modify_product_scene);
app_stage.show();
}
#FXML
private void closeProgram(ActionEvent event) throws IOException {
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.close();
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
// inventoryColumn.setCellValueFactory(cellData -> cellData.getValue().instockProperty().asObject());
// priceColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty().asObject());
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
inventoryColumn.setCellValueFactory(new PropertyValueFactory<>("instock"));
priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
}
public void setMainApp(IMS mainApp) {
this.mainApp = mainApp;
// Add observable list data to the table
partTable.setItems(mainApp.getPartData());
}
#FXML
private void handleDeletePart(){
int selectedIndex = partTable.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0){
partTable.getItems().remove(selectedIndex);
} else {
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("No Part Selected");
alert.setHeaderText("No Part Selected");
alert.setContentText("Please select the part you would like to delete.");
alert.showAndWait();
}
}
}
FXMLDocument.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.control.cell.*?>
<?import javafx.collections.*?>
<?import fxmltableview.*?>
<?import ims.Part?>
<?import ims.Inhouse?>
<?import ims.Outsourced?>
<BorderPane id="main" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ims.FXMLDocumentController" >
<top>
<Label fx:id="mainTitle" text="Inventory Management System" />
</top>
<center>
<HBox fx:id="holding">
<children>
<VBox styleClass="contentBox">
<children>
<HBox styleClass="topBox">
<HBox styleClass="subHeading">
<Label text="Parts" />
</HBox>
<HBox styleClass="searchBox">
<Button text="Search" />
<TextField />
</HBox>
</HBox>
<TableView fx:id="partTable" styleClass="dataTable">
<columns>
<TableColumn fx:id="partIDColumn" text="Part ID" />
<TableColumn fx:id="nameColumn" text="Part Name" />
<TableColumn fx:id="inventoryColumn" text="Inventory Level" />
<TableColumn fx:id="priceColumn" text="Price/Cost per Unit" />
</columns>
</TableView>
<HBox styleClass="modificationButtons">
<children>
<Button onAction="#addPart" text="Add" />
<Button onAction="#modifyPart" text="Modify" />
<Button text="Delete" />
</children>
</HBox>
</children>
</VBox>
<VBox styleClass="contentBox">
<children>
<HBox styleClass="topBox">
<HBox styleClass="subHeading">
<Label text="Products" />
</HBox>
<HBox styleClass="searchBox">
<Button text="Search" />
<TextField />
</HBox>
</HBox>
<TableView fx:id="productTable" styleClass="dataTable">
<columns>
<TableColumn text="Part ID" />
<TableColumn text="Part Name" />
<TableColumn text="Inventory Level" />
<TableColumn text="Price/Cost per Unit" />
</columns>
</TableView>
<HBox styleClass="modificationButtons">
<children>
<Button onAction="#addProduct" text="Add" />
<Button onAction="#modifyProduct" text="Modify" />
<Button text="Delete" />
</children>
</HBox>
</children>
</VBox>
</children>
</HBox>
</center>
<bottom>
<HBox fx:id="exitButton">
<children>
<Button onAction="#closeProgram" text="Exit" />
</children>
</HBox>
</bottom>
</BorderPane>
Part.java
package ims;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
*
* #author chelseacamper
*/
public class Part {
private final SimpleStringProperty name;
private final SimpleIntegerProperty instock;
private final SimpleDoubleProperty price;
private final SimpleIntegerProperty min;
private final SimpleIntegerProperty max;
public Part(){
this("", 0, 0.00, 0, 0);
}
public Part(String name, int instock, double price, int min, int max) {
this.name = new SimpleStringProperty(name);
this.instock = new SimpleIntegerProperty(instock);
this.price = new SimpleDoubleProperty(price);
this.min = new SimpleIntegerProperty(min);
this.max = new SimpleIntegerProperty(max);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public StringProperty nameProperty() {
return name;
}
public Double getPrice() {
return price.get();
}
public void setPrice(Double price) {
this.price.set(price);
}
public DoubleProperty priceProperty(){
return price;
}
public int getInstock() {
return instock.get();
}
public void setInstock(int instock) {
this.instock.set(instock);
}
public IntegerProperty instockProperty(){
return instock;
}
public int getMin() {
return min.get();
}
public void setMin(int min) {
this.min.set(min);
}
public IntegerProperty minProperty(){
return min;
}
public int getMax() {
return max.get();
}
public void setMax(int max) {
this.max.set(max);
}
public IntegerProperty maxProperty(){
return max;
}
}
addPartController.java
package ims;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.stage.Stage;
/**
* FXML Controller class
*
* #author chelseacamper
*/
public class AddPartController implements Initializable {
#FXML
ToggleButton inhouse;
#FXML
ToggleButton outsourced;
#FXML
Label inhouseLabel;
#FXML
Label outsourcedLabel;
#FXML
TextField inhouseTextField;
#FXML
TextField outsourcedTextField;
#FXML
private TableView<Part> partTable;
#FXML
private TextField partNameField;
#FXML
private TextField partInstockField;
#FXML
private TextField partPriceField;
#FXML
private TextField partMaxField;
#FXML
private TextField partMinField;
#FXML
private Button cancel;
#FXML
private Button save;
private Part part = new Part();
// private ObservableList<Part> partData = FXCollections.observableArrayList();
private ObservableList<Part> tableItems;
/**
* Initializes the controller class.
* #param url
* #param rb
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
inhouseLabel.visibleProperty().bind( inhouse.selectedProperty() );
outsourcedLabel.visibleProperty().bind( outsourced.selectedProperty() );
inhouseTextField.visibleProperty().bind( inhouse.selectedProperty() );
outsourcedTextField.visibleProperty().bind( outsourced.selectedProperty() );
inhouseLabel.managedProperty().bind( inhouse.selectedProperty() );
outsourcedLabel.managedProperty().bind( outsourced.selectedProperty() );
inhouseTextField.managedProperty().bind( inhouse.selectedProperty() );
outsourcedTextField.managedProperty().bind( outsourced.selectedProperty() );
}
#FXML
public void addInhouse(ActionEvent event) throws IOException{
// Part tempPart = new Part(partNameField.getText(),
// Integer.parseInt(partInstockField.getText()),
// Double.parseDouble(partPriceField.getText()),
// Integer.parseInt(partMaxField.getText()),
// Integer.parseInt(partMinField.getText()));
// tableItems.add(new Part(partNameField.getText(),
// Integer.parseInt(partInstockField.getText()),
// Double.parseDouble(partPriceField.getText()),
// Integer.parseInt(partMaxField.getText()),
// Integer.parseInt(partMinField.getText())
// ));
part
.setName(partNameField.getText());
part.setPrice(Double.parseDouble(partPriceField.getText()));
part.setInstock(Integer.parseInt(partInstockField.getText()));
part.setMin(Integer.parseInt(partMinField.getText()));
part.setMax(Integer.parseInt(partMaxField.getText()));
System.out.println(partNameField.getText());
Stage stage = (Stage) cancel.getScene().getWindow();
stage.close();
}
#FXML
private void close(ActionEvent event) throws IOException {
Stage stage = (Stage) cancel.getScene().getWindow();
stage.close();
}
void setTableItems(ObservableList<Part> tableItems) {
this.tableItems = tableItems;
}
}
addPart.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane id="addPage" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ims.AddPartController">
<stylesheets>
<String fx:value="style.css" />
</stylesheets>
<fx:define>
<ToggleGroup fx:id="inOutGroup" />
</fx:define>
<center>
<VBox fx:id="verticalHolding">
<children>
<HBox fx:id="topRow">
<Label text="Add Part"/>
<RadioButton fx:id="inhouse" toggleGroup="$inOutGroup" text="In-House"/>
<RadioButton fx:id="outsourced" toggleGroup="$inOutGroup" selected="true" text="Outsourced"/>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="ID" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField promptText="Auto Gen - Disabled" disable="true" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="Name" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField fx:id="partNameField" promptText="Part Name" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="Inv" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField fx:id="partInstockField" promptText="Inv" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="Price/Cost" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField fx:id="partPriceField" promptText="Price/Cost" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label text="Max" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField styleClass="smallTextField" fx:id="partMaxField" promptText="Max" />
<Label text="Min" />
<TextField styleClass="smallTextField" fx:id="partMinField" promptText="Min" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
<Label fx:id="inhouseLabel" text="Machine ID" />
<Label fx:id="outsourcedLabel" text="Company Name" />
</HBox>
<HBox styleClass="halfWidthRight">
<TextField fx:id="inhouseTextField" promptText="Mach ID" />
<TextField fx:id="outsourcedTextField" promptText="Comp Nm" />
</HBox>
</HBox>
<HBox styleClass="fullWidth">
<HBox styleClass="halfWidthLeft">
</HBox>
<HBox styleClass="halfWidthRight">
<Button onAction="#addInhouse" fx:id="save" text="Save" />
<Button onAction="#close" fx:id="cancel" text="Cancel" />
</HBox>
</HBox>
</children>
</VBox>
</center>
</BorderPane>

Related

How to add TableView footer in JavaFx TableView

I am stuck on how to add table footer or column footer in JavaFX TableView. I am looking to add a TableView which will show purchased items with quantities and sells price in columns and total items count and total sum at the TableView footer. I looked at various resources, but could not find footer property associated with TableView. Any idea how to do it?
Model Class
package javafxapplication8;
public class TestModel {
private String itemName = null;
private int pricePerUnit = 0;
private double quantity = 0.0;
private double amount = 0.0;
public TestModel() {
}
public TestModel(String argitemName, int argpricePerUnit, double argquantity, double argamount) {
itemName = argitemName;
pricePerUnit = argpricePerUnit;
quantity = argquantity;
amount = argamount;
}
public void setItemName(String argitemName) {
itemName = argitemName;
}
public void setPricePerUnit(int argpricePerUnit) {
pricePerUnit = argpricePerUnit;
}
public void setQuantity(double argquantity) {
quantity = argquantity;
}
public void setAmount(double argamount) {
amount = argamount;
}
public String getItemName() {
return itemName;
}
public int getPricePerUnit() {
return pricePerUnit;
}
public double getQuantity() {
return quantity;
}
public double getAmount() {
return amount;
}
#Override
public String toString() {
return this.itemName + "" + this.pricePerUnit + "" + this.quantity + "" + this.amount;
}
}
XML Code
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane id="AnchorPane" fx:id="anchor" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication8.TVCTestModel">
<children>
<VBox prefHeight="564.0" prefWidth="857.0">
<children>
<HBox alignment="BOTTOM_LEFT" prefHeight="100.0" prefWidth="1613.0" spacing="20.0" />
<BorderPane prefHeight="695.0" prefWidth="1618.0">
<center>
<VBox prefHeight="544.0" prefWidth="772.0">
<children>
<HBox prefHeight="65.0" prefWidth="1618.0" />
<HBox prefHeight="426.0" prefWidth="857.0">
<children>
<HBox alignment="CENTER" prefHeight="225.0" prefWidth="857.0">
<children>
<TableView fx:id="myTableView" prefHeight="419.0" prefWidth="816.0">
<columns>
<TableColumn fx:id="itemName" prefWidth="200.0" text="Item Name" />
<TableColumn fx:id="pricePerUnit" prefWidth="200.0" text="Price Per Unit" />
<TableColumn fx:id="quantity" prefWidth="200.0" text="Quantity" />
<TableColumn fx:id="amount" prefWidth="200.0" text="Amount" />
</columns>
</TableView>
</children>
</HBox>
</children>
</HBox>
</children>
</VBox>
</center>
<bottom>
</bottom>
</BorderPane>
</children>
</VBox>
</children>
</AnchorPane>
Controller Class
package javafxapplication8;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
public class TVCTestModel implements Initializable {
#FXML
private TableColumn<TestModel, String> itemName;
#FXML
private TableColumn<TestModel, Integer> pricePerUnit;
#FXML
private TableColumn<TestModel, Double> quantity;
#FXML
private TableColumn<TestModel, Double> amount;
#FXML
private TableView<TestModel> myTableView;
public ObservableList<TestModel> objList = FXCollections.observableArrayList();
#FXML
private AnchorPane anchor;
private static TestModel curTestModel;
#Override
public void initialize(URL url, ResourceBundle rb) {
this.itemName.setCellValueFactory(new PropertyValueFactory<>("itemName"));
this.pricePerUnit.setCellValueFactory(new PropertyValueFactory<>("pricePerUnit"));
this.quantity.setCellValueFactory(new PropertyValueFactory<>("quantity"));
this.amount.setCellValueFactory(new PropertyValueFactory<>("amount"));
objList.add(new TestModel("Item 1", 10, 4, 400));
objList.add(new TestModel("Item 2", 20, 5, 1000));
objList.add(new TestModel("Item 3", 30, 6, 1800));
objList.add(new TestModel("Item 4", 400, 7, 2800));
System.out.println(objList.size());
myTableView.setItems(objList);
}
}
MainMethod Class
package javafxapplication8;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class JavaFXApplication8 extends Application {
#Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("TVCTestModel.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException ex) {
Logger.getLogger(JavaFXApplication8.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
launch(args);
}
}
Your updated question was reopened, and the image provided suggests that, instead of a footer, you want two summary fields. As your table is not editable, a simple approximation is illustrated here—add two labels to the view, and iterate the table's model in the controller to establish the localized result:
TVCTestModel.fxml:
…
<bottom>
<HBox alignment="CENTER_RIGHT" style="-fx-spacing: 5px;">
<children>
<Label fx:id="labelQ"/>
<Label fx:id="labelA"/>
</children>
</HBox>
</bottom>
…
TVCTestModel.java
#FXML private Label labelQ;
#FXML private Label labelA;
#Override
public void initialize(URL url, ResourceBundle rb) {
…
double sumQuantity = 0;
double sumAmout = 0;
for (TestModel o : objList) {
sumQuantity += o.getQuantity();
sumAmout += o.getAmount();
}
labelQ.setText("Quantity: "
+ NumberFormat.getNumberInstance().format(sumQuantity));
labelA.setText("Amount: "
+ NumberFormat.getCurrencyInstance().format(sumAmout));
}
If you later decide to make your table editable, as shown here, you should consider these modifications:
Migrate to observable properties in your model class, as shown here.
Create your ObservableList model with an extractor, as shown here and here; your extractor would include properties for quantity and amount; your controller could then update the summary field in a ListChangeListener.

error on running my javafxml application with Derby database

I'm new in Java. I am writing a JavaFXML application in Netbeans IDE 8.2 that includes a class for connecting to a Derby database (DatabaseHandler.java) that first create a database for me. But when i run the program, this database is not created in my project. Does any code is required to added or modified? Here is my codes. Please help me.
my program has 2 packages: -library.assistant.database -library.assistant.ui.addbook
Codes for FXMLDocumentCntroller.java
package library.assistant.ui.addbook;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import library.assistant.database.DatabaseHandler;
/**
* FXML Controller class
*
* #author pc
*/
public class FXMLDocumentController implements Initializable {
#FXML
private JFXTextField title;
#FXML
private JFXTextField id;
#FXML
private JFXTextField author;
#FXML
private JFXTextField publisher;
#FXML
private JFXButton saveButton;
#FXML
private JFXButton cancelButton;
DatabaseHandler databaseHandler;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
databaseHandler = new DatabaseHandler();
}
#FXML
private void addBook(ActionEvent event) {
}
#FXML
private void cancel(ActionEvent event) {
}
}
Codes for DatabaseHandler.java
package library.assistant.database;
private static DatabaseHandler handler;
private static final String DB_URL = "jdbc:derby:database;create=true";
private static Connection conn = null;
private static Statement stmt = null;
public DatabaseHandler() {
createConnection();
setupBookTable();
}
void createConnection() {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
conn = DriverManager.getConnection(DB_URL);
} catch (Exception e) {
e.printStackTrace();
}
}
void setupBookTable() {
String Table_Name = "Book";
try {
stmt = conn.createStatement();
DatabaseMetaData dbm = conn.getMetaData();
ResultSet tables = dbm.getTables(null, null, Table_Name.toUpperCase(), null);
if (tables.next()) {
System.out.println("table" + Table_Name + "already exists. Ready for go!");
} else {
stmt.execute("CREATE TABLE " + Table_Name + "("
+ " id varchar(200) primary key,\n"
+ " title varchar(200),\n"
+ " author varchar(200),\n"
+ " publisher varchar(100),\n"
+ " isAvailable boolaen default true"
+ " )");
}
} catch (SQLException e) {
System.err.println(e.getMessage() + " ... setupDatabase");
} finally {
}
}
}
Codes for LibraryAssistant.java
package library.assistant.ui.addbook;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* #author pc
*/
public class LibraryAssistant extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Here is my fxml file
<?xml version="1.0" encoding="UTF-8"?>
<?import com.jfoenix.controls.JFXButton?>
<?import com.jfoenix.controls.JFXTextField?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane id="AnchorPane" prefHeight="255.0" prefWidth="368.0"
xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="library.assistant.ui.addbook.FXMLDocumentController">
<children>
<VBox prefHeight="363.0" prefWidth="368.0" AnchorPane.bottomAnchor="0.0"
AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0"
AnchorPane.topAnchor="0.0">
<children>
<JFXTextField fx:id="title" labelFloat="true" promptText="Book Title">
<VBox.margin>
<Insets left="10.0" right="10.0" top="20.0" />
</VBox.margin>
</JFXTextField>
<JFXTextField fx:id="id" labelFloat="true" layoutX="20.0"
layoutY="30.0" promptText="Book ID">
<VBox.margin>
<Insets bottom="10.0" left="10.0" right="10.0" top="20.0" />
</VBox.margin>
</JFXTextField>
<JFXTextField fx:id="author" labelFloat="true" layoutX="20.0"
layoutY="30.0" promptText="Book Author">
<VBox.margin>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</VBox.margin>
</JFXTextField>
<JFXTextField fx:id="publisher" labelFloat="true" layoutX="10.0"
layoutY="55.0" promptText="Publisher">
<VBox.margin>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</VBox.margin>
</JFXTextField>
<HBox prefHeight="58.0" prefWidth="368.0">
<children>
<JFXButton fx:id="saveButton" onAction="#addBook"
prefHeight="58.0" prefWidth="200.0" stylesheets="#addbook.css" text="Save"
/>
<JFXButton fx:id="cancelButton" layoutX="10.0" layoutY="10.0"
onAction="#cancel" prefHeight="58.0" prefWidth="200.0"
stylesheets="#addbook.css" text="Cancel" />
</children>
</HBox>
</children>
</VBox>
</children>
</AnchorPane>

Javafx cannot update the text for tempDisplay label

I cannot set the text for the tempDisplay label by using settext() in connectArduino method. It only can show part of the string, like the symbol "°C", just like the screen shot shows. But the string "input" can be print out actually.
Here is my controller class
import javafx.application.Platform;
import javafx.scene.chart.LineChart;
import javafx.scene.control.*;
import javafx.event.ActionEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ToggleButton;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
import jssc.SerialPort;
import static jssc.SerialPort.MASK_RXCHAR;
import jssc.SerialPortEvent;
import jssc.SerialPortException;
import jssc.SerialPortList;
public class MainController {
SerialPort arduinoPort = null;
ObservableList<String> portList;
public String input;
public static double max;
public static double min;
public static String phoneNumber;
public static final String ACCOUNT_SID =
"AC935209d3c44660b4a550e3380249857a";
public static final String AUTH_TOKEN = "42bcd28e23344404c737eb3499d2a747";
final int NUM_OF_POINT = 300;
XYChart.Series series;
#FXML
private ComboBox comboBox;
#FXML
private ToggleButton modeButton;
#FXML
private ToggleButton ledButton;
#FXML
private Button connectButton;
#FXML
private TextArea displayArea;
#FXML
private Label tempDisplay;
#FXML
private NumberAxis xAxis;
#FXML
private NumberAxis yAxis;
#FXML
private LineChart lineChart;
#FXML
private void initialize(){
displayArea.setEditable(false);
detectPort();
comboBox.setPromptText("Port List");
comboBox.setItems(portList);
setLineChart();
//sendSMS();
}
private void detectPort(){
portList = FXCollections.observableArrayList();
String[] serialPortNames = SerialPortList.getPortNames();
portList.addAll(serialPortNames);
}
private void connect(){
disconnectArduino();
if(connectButton.getText().equals("Connect")) {
connectArduino(comboBox.getValue().toString());
}
ledButton.setSelected(false);
}
public boolean connectArduino(String port){
displayArea.appendText("connect Arduino");
if(port.isEmpty()){
alert("Connect Failed!");
return false;
}
else {
connectButton.setText("Disconnect");
boolean success = false;
SerialPort serialPort = new SerialPort(port);
try {
serialPort.openPort();
serialPort.setParams(
SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setEventsMask(MASK_RXCHAR);
serialPort.addEventListener((SerialPortEvent serialPortEvent) -> {
if (serialPortEvent.isRXCHAR()) {
try {
input = serialPort.readString(serialPortEvent
.getEventValue());
System.out.println(input);
if (input.contains("false")) {
alert("Unplugged Sensor");
} else {
Platform.runLater(() -> {
String st = input + " °C";
tempDisplay.setText(st);
// shiftSeriesData(Float.parseFloat(input));
});
}
} catch (SerialPortException ex) {
Logger.getLogger(MainController.class.getName())
.log(Level.SEVERE, null, ex);
alert("No Data Available");
}
}
});
arduinoPort = serialPort;
success = true;
} catch (SerialPortException ex) {
Logger.getLogger(MainController.class.getName())
.log(Level.SEVERE, null, ex);
System.out.println("SerialPortException: " + ex.toString());
alert("No Data Available");
}
return success;
}
}
Here is my fxml class
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.chart.LineChart?>
<?import javafx.scene.chart.NumberAxis?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.ToggleButton?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="627.0" prefWidth="664.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="MainController">
<children>
<LineChart fx:id="lineChart" createSymbols="false" layoutY="74.0" prefHeight="343.0" prefWidth="396.0" title="Temperature of Session">
<xAxis>
<NumberAxis autoRanging="false" label="Time (s)" side="BOTTOM" tickUnit="100" fx:id="xAxis" upperBound="300"/>
</xAxis>
<yAxis>
<NumberAxis fx:id="yAxis" autoRanging="false" label="Temperature (°C)" lowerBound="10" side="RIGHT" upperBound="50" />
</yAxis>
</LineChart>
<TextArea fx:id="displayArea" editable="false" layoutX="15.0" layoutY="426.0" prefHeight="186.0" prefWidth="635.0" />
<Label layoutX="94.0" layoutY="14.0" prefHeight="60.0" prefWidth="482.0" text="Team Placeholder Themometer Interface">
<font>
<Font size="24.0" />
</font>
</Label>
<Button fx:id="connectButton" layoutX="475.0" layoutY="145.0" mnemonicParsing="false" onAction="#connectPressed" prefHeight="80.0" prefWidth="131.0" text="Connect">
<font>
<Font size="18.0" />
</font>
</Button>
<Button fx:id="setButton" layoutX="475.0" layoutY="241.0" mnemonicParsing="false" onAction="#setPressed" prefHeight="34.0" prefWidth="131.0" text="Set SMS" />
<Label layoutX="400.0" layoutY="314.0" prefHeight="27.0" prefWidth="131.0" text="Current Temperature" />
<ComboBox fx:id="comboBox" layoutX="475.0" layoutY="94.0" prefHeight="34.0" prefWidth="131.0" />
<ToggleButton fx:id="ledButton" layoutX="540.0" layoutY="360.0" mnemonicParsing="false" onAction="#ledPressed" prefHeight="34.0" prefWidth="109.0" text="Show on LEDs" />
<ToggleButton fx:id="modeButton" layoutX="540.0" layoutY="314.0" mnemonicParsing="false" onAction="#modePressed" prefHeight="34.0" prefWidth="109.0" text="In Fahrenheit" />
<Label fx:id="tempDisplay" layoutX="400.0" layoutY="341.0" prefHeight="39.0" prefWidth="131.0" textFill="#e10707">
<font>
<Font size="32.0" />
</font>
</Label>
</children>
Screen shot for the interface

Load Exception in fxml

I want my inventory_layout to load when i click on the first button but i am getting load exception there while the same code works fine with other fxmls.
Path of controller is right.
fxml is in the right place.
Here is my code- Inventory
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Border;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import pharmbooks.Utils.DbSingleton;
import pharmbooks.Utils.UIController;
import java.io.IOException;
public class MainController {
#FXML
private BorderPane borderPane;
#FXML
public void initInventory(ActionEvent actionEvent) throws IOException{
UIController<InventoryController> uiController=new UIController<InventoryController>();
uiController.setUp(borderPane,"inventory_layout.fxml");
}
public void initPurchase(ActionEvent actionEvent) throws IOException{
UIController<PurchaseController> uiController=new UIController<>();
uiController.setUp(borderPane,"purchase_layout.fxml");
}
}
Ui Controller
public class UIController<T> {
private T controller;
private Pane pane;
public T getController() {
return controller;
}
public void setUp(Pane mainPane,String fxmlLocation){
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getClassLoader().getResource(fxmlLocation));
pane = loader.load();
controller = loader.getController();
mainPane.getChildren().clear();
mainPane.getChildren().add(pane);
}catch (Exception e){
System.out.println(UIController.class.getSimpleName()+" "+e.toString());
}
} }
This code works well in ubuntu though :/
here is the error :
UIController javafx.fxml.LoadException:
/Users/manyamadan/Desktop/Everything/pharmbooks-v2/target/classes/inventory_layout.fxml
Inventory controller :
public class InventoryController implements Initializable{
public TableColumn batchId;
public TableColumn company;
public TableColumn name;
public TableColumn packing;
public TableColumn quantity;
public TableColumn expiry;
public TableColumn mrp;
#FXML
private TableView<Inventory> personTable;
public void InventoryController()
{
}
public void initialize(URL location, ResourceBundle resources) {
batchId.setCellValueFactory(new PropertyValueFactory<Inventory, String>("BATCH_ID"));
company.setCellValueFactory(new PropertyValueFactory<Inventory, String>("COMPANY"));
name.setCellValueFactory(new PropertyValueFactory<Inventory, String>("PRODUCT_NAME"));
packing.setCellValueFactory(new PropertyValueFactory<Inventory, String>("PACKING"));
quantity.setCellValueFactory(new PropertyValueFactory<Inventory, Integer>("QUANTITY"));
expiry.setCellValueFactory(new PropertyValueFactory<Inventory, String>("EXPIRY_DATE"));
mrp.setCellValueFactory(new PropertyValueFactory<Inventory, String>("MRP"));
personTable.setEditable(true);
personTable.setItems(InventoryData.getInstance().getList());
// name.setOnEditCommit(TableColumn.CellEditEvent(Inventory,String)event);
Inventory inventory_data = personTable.getSelectionModel().getSelectedItem();
System.out.println(inventory_data.getPRODUCT_NAME()+ "" + inventory_data.getBATCH_ID());
personTable.setOnKeyPressed(event -> {
TablePosition<Inventory, ?> pos = personTable.getFocusModel().getFocusedCell() ;
if (pos != null) {
AnchorPane anchorPane= null;
try {
anchorPane = FXMLLoader.load(getClass().getClassLoader().getResource("edit_inventory_data.fxml"));
} catch (IOException e) {
e.printStackTrace();
}
Stage stage=new Stage();
stage.setTitle("Apna Dialog");
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(StageManager.getInstance().getPrimaryStage());
Scene scene = new Scene(anchorPane);
stage.setScene(scene);
stage.showAndWait();
}
});
name.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Inventory, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Inventory, String> t) {
System.out.println("ON edit commit" + t);
((Inventory) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setPRODUCT_NAME(t.getNewValue());
}
}
);
}
#FXML
public void addData(ActionEvent actionEvent) throws IOException {
AnchorPane anchorPane= FXMLLoader.load(getClass().getClassLoader().getResource("add_data_inventory.fxml"));
Stage stage=new Stage();
stage.setTitle("Apna Dialog");
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(StageManager.getInstance().getPrimaryStage());
Scene scene = new Scene(anchorPane);
stage.setScene(scene);
stage.showAndWait();
personTable.setItems(InventoryData.getInstance().getList());
}
}
inventory_layout.fxml
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<BorderPane maxHeight="600.0" maxWidth="800.0" prefHeight="600.0" prefWidth="800.0" stylesheets="#beautify_inventory.css" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="pharmbooks.controllers.InventoryController">
<center>
<TableView fx:id="personTable" prefWidth="10000.0" BorderPane.alignment="CENTER">
<columns>
<TableColumn fx:id="batchId" prefWidth="75.0" text="BatchId" />
<TableColumn fx:id="packing" prefWidth="75.0" text="packing" />
<TableColumn fx:id="quantity" prefWidth="75.0" text="quantity" />
<TableColumn fx:id="expiry" prefWidth="75.0" text="expiry" />
<TableColumn fx:id="mrp" prefWidth="75.0" text="mrp" />
</columns>
</TableView>
</center>
<top>
<HBox prefHeight="67.0" prefWidth="800.0" BorderPane.alignment="CENTER">
<children>
<TextField prefHeight="47.0" prefWidth="163.00009155273438">
<HBox.margin>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
</HBox.margin>
</TextField>
<Button mnemonicParsing="false" onAction="#addData" text="Button">
<HBox.margin>
<Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
</HBox.margin>
</Button>
<Button mnemonicParsing="false" prefHeight="39.0" prefWidth="121.0" text="Button">
<HBox.margin>
<Insets bottom="20.0" right="20.0" top="20.0" />
</HBox.margin>
</Button>
<Button mnemonicParsing="false" prefHeight="39.0" prefWidth="129.0" text="Button">
<HBox.margin>
<Insets bottom="20.0" top="20.0" />
</HBox.margin>
</Button>
</children>
</HBox>
</top>
</BorderPane>
In inventory_layout.fxml you set fx:id attribute to all table columns:
<TableColumn fx:id="batchId" prefWidth="75.0" text="BatchId" />
<TableColumn fx:id="packing" prefWidth="75.0" text="packing" />
<TableColumn fx:id="quantity" prefWidth="75.0" text="quantity" />
<TableColumn fx:id="expiry" prefWidth="75.0" text="expiry" />
<TableColumn fx:id="mrp" prefWidth="75.0" text="mrp" />
but in InventoryController you does not annotate this components with #FXML. Witout this annotations FXMLLoader will not be able to inject correct objects to controller. Correct code:
#FXML
public TableColumn batchId;
#FXML
public TableColumn company;
#FXML
public TableColumn name;
#FXML
public TableColumn packing;
#FXML
public TableColumn quantity;
#FXML
public TableColumn expiry;
#FXML
public TableColumn mrp;
I'm guessing that you get NullPointerException in initalize() method when you try to setCellValueFactory() on table columns.
I assume that you are accessing fxml resource files correctly.

JavaFX, initialize setCellValueFactory for TableView with bean and bigDecimal, result -> NullPointerException

i'm new to JavaFX and i want to print some BigDecimal and Bean in TableColumn in my TableView.
The issue is that i get a NullPointerExceptionexception when i try to setItems of the TableView.
Just to be clear i'm using the fxml with scenario builder for the graphic (panel, tableView, etc.) and the java class for link the bean's data to the tableView. I'm using the ObservableList for get the change, and the Bean has the correct getter that return ObjectProperty<BigDecimal> or ObjectProperty<ContoBean>.
I don't know if what i'm using for setCellValueFactory is correct, i've tryed to follow the tutorial here, but in this tutorial the TableColumn are set only as String. I've read some example for do the the setCellValueFactory, but as far as i can see the best procedure is to avoid using PropertyValueFactory and trying to stick to lambda expressions (more safe and keep the data type intact using a cellFactory, correct me if i'm wrong).
My question are:
What's the best practies for use setCellValueFactory of TableColumn with BigDecimal and Bean?
The best way is to create the TableColumns with scenario builder and link them with the controller or create only the TableView, in scenario builder, and create each single TableColumn in the java controller?
If i'm using a Bean that contains other Beans, how the TableColumn will represent the information? Which variable will be used for view the information, all of the Bean's variable or only a single one?
MovimentoOverview.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="900.0" prefWidth="1400.0" stylesheets="#DarkTheme.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="it.evil.money.view.MovimentoOverviewController">
<children>
<SplitPane dividerPositions="0.12857142857142856" prefHeight="300.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<TreeView layoutX="-9.0" layoutY="14.0" prefHeight="891.0" prefWidth="200.0" AnchorPane.bottomAnchor="5.0" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="5.0" />
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0" styleClass="background">
<children>
<Label layoutX="14.0" layoutY="7.0" styleClass="label-header" text="Person Details" AnchorPane.leftAnchor="5.0" AnchorPane.topAnchor="5.0">
<font>
<Font size="18.0" />
</font></Label>
<ToolBar layoutX="216.0" layoutY="258.0" prefHeight="40.0" styleClass="background" AnchorPane.bottomAnchor="10.0" AnchorPane.rightAnchor="10.0">
<items>
<Button mnemonicParsing="false" onAction="#handleNewMovimento" text="New.." />
<Button mnemonicParsing="false" onAction="#handleEditMovimento" text="Edit.." />
<Button alignment="CENTER_RIGHT" mnemonicParsing="false" onAction="#handleDeleteMovimento" text="Delete.." textAlignment="CENTER" />
</items>
</ToolBar>
<TableView layoutX="5.0" layoutY="55.0" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="100.0" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="60.0">
<columns>
<TableColumn fx:id="idColumn" prefWidth="75.0" text="ID" />
<TableColumn fx:id="contoColumn" prefWidth="75.0" text="Conto" />
<TableColumn fx:id="dataColumn" prefWidth="75.0" text="Data" />
<TableColumn fx:id="valutaColumn" prefWidth="75.0" text="Valuta" />
<TableColumn fx:id="importoColumn" prefWidth="75.0" text="Importo" />
<TableColumn fx:id="quotaTicketColumn" prefWidth="75.0" text="Quota Ticket" />
<TableColumn fx:id="causaleColumn" prefWidth="75.0" text="Causale" />
<TableColumn fx:id="noteColumn" prefWidth="75.0" text="Note" />
<TableColumn fx:id="tipoPagamentoColumn" prefWidth="75.0" text="Tipo Pagamento" />
<TableColumn fx:id="tipoMovimentoColumn" prefWidth="75.0" text="Tipo Movimento" />
<TableColumn fx:id="spesaInComuneColumn" prefWidth="75.0" text="Spesa in Comune" />
<TableColumn fx:id="spesaPerLavoroColumn" prefWidth="75.0" text="Spesa per Lavoro" />
<TableColumn fx:id="utenteColumn" prefWidth="75.0" text="Utente" />
<TableColumn fx:id="tagColumn" prefWidth="75.0" text="Tag" />
<TableColumn fx:id="bustaPagaColumn" prefWidth="75.0" text="Busta Paga" />
</columns>
</TableView>
</children>
</AnchorPane>
</items>
</SplitPane>
</children>
</AnchorPane>
MovimentoOverviewController
package it.evil.money.view;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.math.BigDecimal;
import java.time.LocalDate;
import it.evil.money.MainApp;
import it.evil.money.model.BustaPagaBean;
import it.evil.money.model.CausaleBean;
import it.evil.money.model.ContoBean;
import it.evil.money.model.MovimentoBean;
import it.evil.money.model.TagBean;
import it.evil.money.model.TipoMovimentoBean;
import it.evil.money.model.TipoPagamentoBean;
import it.evil.money.model.UtenteBean;
import it.evil.money.util.DateUtil;
public class MovimentoOverviewController {
#FXML
private TableView<MovimentoBean> movimentoTable;
#FXML
private TableColumn<MovimentoBean, BigDecimal> idColumn;
#FXML
private TableColumn<MovimentoBean, ContoBean> contoColumn;
#FXML
private TableColumn<MovimentoBean, LocalDate> dataColumn;
#FXML
private TableColumn<MovimentoBean, String> valutaColumn;
#FXML
private TableColumn<MovimentoBean, BigDecimal> importoColumn;
#FXML
private TableColumn<MovimentoBean, BigDecimal> quotaTicketColumn;
#FXML
private TableColumn<MovimentoBean, CausaleBean> causaleColumn;
#FXML
private TableColumn<MovimentoBean, String> noteColumn;
#FXML
private TableColumn<MovimentoBean, TipoPagamentoBean> tipoPagamentoColumn;
#FXML
private TableColumn<MovimentoBean, TipoMovimentoBean> tipoMovimentoColumn;
#FXML
private TableColumn<MovimentoBean, Boolean> spesaInComuneColumn;
#FXML
private TableColumn<MovimentoBean, Boolean> spesaPerLavoroColumn;
#FXML
private TableColumn<MovimentoBean, BustaPagaBean> bustaPagaColumn;
#FXML
private TableColumn<MovimentoBean, UtenteBean> utenteColumn;
#FXML
private TableColumn<MovimentoBean, TagBean> tagColumn;
#FXML
private Label idLabel;
#FXML
private Label contoLabel;
#FXML
private Label dataLabel;
#FXML
private Label valutaLabel;
#FXML
private Label importoLabel;
// Reference to the main application.
private MainApp mainApp;
public MovimentoOverviewController() {
}
#FXML
private void initialize() {
idColumn.setCellValueFactory(cellData -> cellData.getValue().idProperty() );
contoColumn.setCellValueFactory(cellData -> cellData.getValue().contoProperty() );
dataColumn.setCellValueFactory(cellData -> cellData.getValue().dataProperty() );
valutaColumn.setCellValueFactory(cellData -> cellData.getValue().valutaProperty() );
importoColumn.setCellValueFactory(cellData -> cellData.getValue().importoProperty() );
quotaTicketColumn.setCellValueFactory(cellData -> cellData.getValue().quotaTicketProperty() );
causaleColumn.setCellValueFactory(cellData -> cellData.getValue().causaleProperty() );
noteColumn.setCellValueFactory(cellData -> cellData.getValue().noteProperty() );
tipoPagamentoColumn.setCellValueFactory(cellData -> cellData.getValue().tipoPagamentoProperty() );
tipoMovimentoColumn.setCellValueFactory(cellData -> cellData.getValue().tipoMovimentoProperty() );
spesaInComuneColumn.setCellValueFactory(cellData -> cellData.getValue().spesaInComuneProperty() );
spesaPerLavoroColumn.setCellValueFactory(cellData -> cellData.getValue().spesaPerLavoroProperty() );
bustaPagaColumn.setCellValueFactory(cellData -> cellData.getValue().bustaPagaProperty() );
utenteColumn.setCellValueFactory(cellData -> cellData.getValue().utenteProperty() );
tagColumn.setCellValueFactory(cellData -> cellData.getValue().tagProperty() );
}
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
movimentoTable.setItems(mainApp.getMovimentoData());
}
}
MainApp
package it.evil.money;
import java.io.IOException;
import it.evil.money.dao.DatabaseManager;
import it.evil.money.dao.MovimentoDao;
import it.evil.money.model.*;
import it.evil.money.view.*;
import javafx.application.Application;
import javafx.collections.*;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class MainApp extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
private ObservableList<MovimentoBean> movimentoData = FXCollections.observableArrayList();
private MovimentoDao movimentoDao;
public MainApp() {
movimentoDao = new MovimentoDao(DatabaseManager.getConnection());
// Instead of use a empty bean...
// movimentoData.add(new MovimentoBean());
// I get the data for db
movimentoData.addAll(this.movimentoDao.getAll());
this.movimentoDao.distruttore();
}
public ObservableList<MovimentoBean> getMovimentoData() {
return movimentoData;
}
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("AddressApp");
this.primaryStage.getIcons().add(new Image("file:resources/images/address_book_32.png"));
initRootLayout();
showMovimentoOverview();
}
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void showMovimentoOverview() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/MovimentoOverview.fxml"));
AnchorPane personOverview = (AnchorPane) loader.load();
rootLayout.setCenter(personOverview);
MovimentoOverviewController controller = loader.getController();
controller.setMainApp(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
MovimentoBean
package it.evil.money.model;
import java.time.LocalDate;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import java.math.BigDecimal;
public class MovimentoBean {
private final ObjectProperty<BigDecimal> id;
private final ObjectProperty<ContoBean> conto;
private final ObjectProperty<LocalDate> data;
private final StringProperty valuta;
private final ObjectProperty<BigDecimal> importo;
private final ObjectProperty<BigDecimal> quotaTicket;
private final ObjectProperty<CausaleBean> causale;
private final StringProperty note;
private final ObjectProperty<TipoPagamentoBean> tipoPagamento;
private final ObjectProperty<TipoMovimentoBean> tipoMovimento;
private final BooleanProperty spesaInComune;
private final BooleanProperty spesaPerLavoro;
private final ObjectProperty<BustaPagaBean> bustaPaga;
private final ObjectProperty<UtenteBean> utente;
private final ObjectProperty<TagBean> tag;
public MovimentoBean() {
this(null, null, null, null, null, null, null, null, null, null, false, false, null, null, null);
}
public MovimentoBean(BigDecimal id, ContoBean conto, LocalDate data, String valuta, BigDecimal importo,
BigDecimal quotaTicket, CausaleBean causale, String note, TipoPagamentoBean tipoPagamento,
TipoMovimentoBean tipoMovimento, boolean spesaInComune, boolean spesaPerLavoro, BustaPagaBean bustaPaga,
UtenteBean utente, TagBean tag) {
this.id = new SimpleObjectProperty<BigDecimal>(id);
this.conto = new SimpleObjectProperty<ContoBean>(conto);
this.data = new SimpleObjectProperty<LocalDate>(data);
this.valuta = new SimpleStringProperty(valuta);
this.importo = new SimpleObjectProperty<BigDecimal>(importo);
this.quotaTicket = new SimpleObjectProperty<BigDecimal>(quotaTicket);
this.causale = new SimpleObjectProperty<CausaleBean>(causale);
this.note = new SimpleStringProperty(note);
this.tipoPagamento = new SimpleObjectProperty<TipoPagamentoBean>(tipoPagamento);
this.tipoMovimento = new SimpleObjectProperty<TipoMovimentoBean>(tipoMovimento);
this.spesaInComune = new SimpleBooleanProperty(spesaInComune);
this.spesaPerLavoro = new SimpleBooleanProperty(spesaPerLavoro);
this.bustaPaga = new SimpleObjectProperty<BustaPagaBean>(bustaPaga);
this.utente = new SimpleObjectProperty<UtenteBean>(utente);
this.tag = new SimpleObjectProperty<TagBean>(tag);
}
public BigDecimal getId(){
return this.id.get();
}
public void setId(BigDecimal id){
this.id.set(id);
}
public ObjectProperty<BigDecimal> idProperty(){
return id;
}
......
When i start the program i get this error:
Exception in Application start method
java.lang.reflect.InvocationTargetException
.......
Caused by: java.lang.NullPointerException
at it.evil.money.view.MovimentoOverviewController.setMainApp(MovimentoOverviewController.java )
at it.evil.money.MainApp.showMovimentoOverview(MainApp.java )
at it.evil.money.MainApp.start(MainApp.java )

Resources