javaFX controllers doesn't communicate which each other - javafx

i have a problem with javaFX.I'm doing calculator and i divide my app between 3 FXML files(1 is a controller which controlls only numbers and operators, 2 is a controller for textfield which is result field, and last one should let them communicate which each other).
I can not manage how can i write my own method which for example put number "3" when i press number 3 in textfield-which is in other FXML and has its own fxml file.There is a nullpointer exception so i suppose im not initializing this textfield.Please help me with this problem.Is there any way to write my own method(in this example i wrote showDigit()) in MainController class - this method should set Text to textfield after pressing button - for example button 2 will put "2" in textfield.
Below I've pasted my code.
package pl.calculator.controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
public class MainPaneController implements Initializable {
#FXML
private TextPaneController textPaneController;
#FXML
private CalculatorPaneController calculatorPaneController;
#Override
public void initialize(URL location, ResourceBundle resources) {
/*calculatorPaneController.getButtonZero().setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
textPaneController.getTextFieldExpression().setText("example");
}
});*/ --- < THIS WORKS
}
}
FXML for MainController
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<VBox xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="pl.calculator.controller.MainPaneController">
<children>
<fx:include fx:id="textPane" source="TextPane.fxml" />
<fx:include fx:id="calculatorPane" source="CalculatorPane.fxml" />
</children>
</VBox>
Number and operation controller:
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
public class CalculatorPaneController implements Initializable {
#FXML
private Button buttonFour;
#FXML
private Button buttonSix;
#FXML
private Button buttonDivide;
#FXML
private Button buttonOne;
#FXML
private Button buttonCloseBracket;
#FXML
private Button buttonDot;
#FXML
private Button buttonClear;
#FXML
private Button buttonTwo;
#FXML
private Button buttonSeven;
#FXML
private Button buttonOpenBracket;
#FXML
private Button buttonThree;
#FXML
private Button buttonMultiply;
#FXML
private Button buttonSubtract;
#FXML
private Button buttonEight;
#FXML
private Button buttonEqual;
#FXML
private Button buttonNine;
#FXML
private Button buttonZero;
#FXML
private Button buttonMemory;
#FXML
private Button buttonFive;
#FXML
private GridPane gridPane;
#FXML
private Button buttonAdd;
#FXML
private TextPaneController textPaneController;
#FXML
private CalculatorPaneController calculatorPaneController;
#Override
public void initialize(URL location, ResourceBundle resources) {
}
#FXML
private void showDigit(ActionEvent event) {
textPaneController.getTextFieldExpression().setText("s");
} <---------THIS ONE DOESNT WORK
public Button getButtonFour() {
return buttonFour;
}
public void setButtonFour(Button buttonFour) {
this.buttonFour = buttonFour;
}
public Button getButtonSix() {
return buttonSix;
}
public void setButtonSix(Button buttonSix) {
this.buttonSix = buttonSix;
}
public Button getButtonDivide() {
return buttonDivide;
}
public void setButtonDivide(Button buttonDivide) {
this.buttonDivide = buttonDivide;
}
public Button getButtonOne() {
return buttonOne;
}
public void setButtonOne(Button buttonOne) {
this.buttonOne = buttonOne;
}
public Button getButtonCloseBracket() {
return buttonCloseBracket;
}
public void setButtonCloseBracket(Button buttonCloseBracket) {
this.buttonCloseBracket = buttonCloseBracket;
}
public Button getButtonDot() {
return buttonDot;
}
public void setButtonDot(Button buttonDot) {
this.buttonDot = buttonDot;
}
public Button getButtonClear() {
return buttonClear;
}
public void setButtonClear(Button buttonClear) {
this.buttonClear = buttonClear;
}
public Button getButtonTwo() {
return buttonTwo;
}
public void setButtonTwo(Button buttonTwo) {
this.buttonTwo = buttonTwo;
}
public Button getButtonSeven() {
return buttonSeven;
}
public void setButtonSeven(Button buttonSeven) {
this.buttonSeven = buttonSeven;
}
public Button getButtonOpenBracket() {
return buttonOpenBracket;
}
public void setButtonOpenBracket(Button buttonOpenBracket) {
this.buttonOpenBracket = buttonOpenBracket;
}
public Button getButtonThree() {
return buttonThree;
}
public void setButtonThree(Button buttonThree) {
this.buttonThree = buttonThree;
}
public Button getButtonMultiply() {
return buttonMultiply;
}
public void setButtonMultiply(Button buttonMultiply) {
this.buttonMultiply = buttonMultiply;
}
public Button getButtonSubtract() {
return buttonSubtract;
}
public void setButtonSubtract(Button buttonSubtract) {
this.buttonSubtract = buttonSubtract;
}
public Button getButtonEight() {
return buttonEight;
}
public void setButtonEight(Button buttonEight) {
this.buttonEight = buttonEight;
}
public Button getButtonEqual() {
return buttonEqual;
}
public void setButtonEqual(Button buttonEqual) {
this.buttonEqual = buttonEqual;
}
public Button getButtonNine() {
return buttonNine;
}
public void setButtonNine(Button buttonNine) {
this.buttonNine = buttonNine;
}
public Button getButtonZero() {
return buttonZero;
}
public void setButtonZero(Button buttonZero) {
this.buttonZero = buttonZero;
}
public Button getButtonMemory() {
return buttonMemory;
}
public void setButtonMemory(Button buttonMemory) {
this.buttonMemory = buttonMemory;
}
public Button getButtonFive() {
return buttonFive;
}
public void setButtonFive(Button buttonFive) {
this.buttonFive = buttonFive;
}
public GridPane getGridPane() {
return gridPane;
}
public void setGridPane(GridPane gridPane) {
this.gridPane = gridPane;
}
public Button getButtonAdd() {
return buttonAdd;
}
public void setButtonAdd(Button buttonAdd) {
this.buttonAdd = buttonAdd;
}
}
FXML for operation and number controller:
<?import java.lang.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<GridPane fx:id="gridPane" prefHeight="308.0" prefWidth="375.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="pl.calculator.controller.CalculatorPaneController">
<children>
<Button fx:id="buttonOne" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" onAction="#showDigit" text="1" />
<Button fx:id="buttonFour" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="4" GridPane.rowIndex="1" />
<Button fx:id="buttonTwo" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="2" GridPane.columnIndex="1" />
<Button fx:id="buttonSeven" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="7" GridPane.rowIndex="2" />
<Button fx:id="buttonFive" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="5" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<Button fx:id="buttonEight" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="8" GridPane.columnIndex="1" GridPane.rowIndex="2" />
<Button fx:id="buttonThree" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="3" GridPane.columnIndex="2" />
<Button fx:id="buttonSix" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="6" GridPane.columnIndex="2" GridPane.rowIndex="1" />
<Button fx:id="buttonNine" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="9" GridPane.columnIndex="2" GridPane.rowIndex="2" />
<Button fx:id="buttonZero" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="0" GridPane.rowIndex="3" />
<Button fx:id="buttonDot" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="." GridPane.columnIndex="1" GridPane.rowIndex="3" />
<Button fx:id="buttonEqual" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="=" GridPane.columnIndex="2" GridPane.rowIndex="3" />
<Button fx:id="buttonDivide" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="/" GridPane.columnIndex="3" GridPane.rowIndex="2" />
<Button fx:id="buttonMultiply" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="*" GridPane.columnIndex="3" GridPane.rowIndex="3" />
<Button fx:id="buttonSubtract" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="-" GridPane.columnIndex="3" GridPane.rowIndex="1" />
<Button fx:id="buttonAdd" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="+" GridPane.columnIndex="3" />
<Button fx:id="buttonCloseBracket" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text=")" GridPane.columnIndex="4" GridPane.rowIndex="3" />
<Button fx:id="buttonOpenBracket" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="(" GridPane.columnIndex="4" GridPane.rowIndex="2" />
<Button fx:id="buttonMemory" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="M" GridPane.columnIndex="4" />
<Button fx:id="buttonClear" minHeight="40.0" minWidth="40.0" mnemonicParsing="false" text="C" GridPane.columnIndex="4" GridPane.rowIndex="1" />
</children>
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
<ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
<RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
</rowConstraints>
</GridPane>
Controller for textfields(results)
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class TextPaneController {
#FXML
private Label labelExpression;
#FXML
private TextField textFieldOnp;
#FXML
private Label labelOnp;
#FXML
private TextField textFieldExpression;
public Label getLabelExpression() {
return labelExpression;
}
public void setLableExpression(Label lableExpression) {
this.labelExpression = lableExpression;
}
public TextField getTextFieldOnp() {
return textFieldOnp;
}
public void setTextFieldOnp(TextField textFieldOnp) {
this.textFieldOnp = textFieldOnp;
}
public Label getLabelOnp() {
return labelOnp;
}
public void setLabelOnp(Label labelOnp) {
this.labelOnp = labelOnp;
}
public TextField getTextFieldExpression() {
return textFieldExpression;
}
public void setTextFieldExpression(TextField textFieldExpression) {
this.textFieldExpression = textFieldExpression;
}
}
FXML File for TExt:
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="89.0" prefWidth="349.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="pl.calculator.controller.TextPaneController">
<children>
<Label fx:id="lableExpression" layoutX="21.0" layoutY="14.0" text="Wprowadź wyrażenie:" />
<Label fx:id="labelOnp" layoutX="213.0" layoutY="14.0" text="Wyrażenie ONP" />
<TextField fx:id="textFieldExpression" layoutX="5.0" layoutY="45.0" />
<TextField fx:id="textFieldOnp" editable="false" layoutX="180.0" layoutY="45.0" />
</children>
</AnchorPane>
and stack trace:
TextField[id=textFieldExpression, styleClass=text-input text-field]
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(Unknown Source)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1800(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(Unknown Source)
at com.sun.glass.ui.win.WinApplication$4$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
... 48 more
Caused by: java.lang.NullPointerException
at pl.calculator.controller.CalculatorPaneController.showDigit(CalculatorPaneController.java:89)
... 57 more

The FXML file CalculatorPane.fxml doesn't have an <fx:include fx:id="textPane" ... />, so the associated controller doesn't get a textPaneController injected into it. Thus textPaneController in CalculatorPaneController is null, and you get the NullPointerException.
A way to update the value from the CalculatorPaneController is to give both controllers a shared data model, and update the model. So you could do something like
public class DataModel {
private final StringProperty text = new SimpleStringProperty();
public StringProperty textProperty() {
return text ;
}
public final String getText() {
return textProperty().get();
}
public final void setText(String text) {
textProperty().set(text);
}
// other properties as needed...
}
Then you controllers can do
public class TextPaneController {
private DataModel model ;
#FXML
private TextField textFieldExpression ;
// etc ...
public void setModel(DataModel model) {
this.model = model ;
textFieldExpression.textProperty().bindBidirectional(model.textProperty());
}
}
and
public class CalculatorPaneController {
private DataModel model ;
public void setModel(DataModel model) {
this.model = model ;
}
// ...
#FXML
private void showDigit(ActionEvent event) {
model.setText("s");
}
}
Finally, you tie everything together in the main controller's initialize method:
public class MainPaneController implements Initializable {
#FXML
private TextPaneController textPaneController;
#FXML
private CalculatorPaneController calculatorPaneController;
#Override
public void initialize(URL location, ResourceBundle resources) {
DataModel model = new DataModel();
textPaneController.setModel(model);
calculatorPaneController.setModel(model);
}
}
You really don't need (and shouldn't have) all the get/set methods for the controls in the controllers. Those should be kept private and not exposed outside the controller.

Related

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 - populating data from TableView selection to dialog box

I am learning to get data from selected row of TableView and prepopulate dialog box with that data. No matter what I do while loading dialog box I get NullPointerException in Controller.java -> showEditContactDialog()-> editController.setItem(item)).Somehow I am not able to pass selected data to another class and have it displayed by dialog box. Appreciate someone point me to the right direction. Here is the code:
Main.java:
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import sample.datamodel.ContactData;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("MainWindow.fxml"));
primaryStage.setTitle("Address Book");
primaryStage.setScene(new Scene(root, 1280, 500));
primaryStage.show();
}
#Override
public void stop(){
ContactData.getInstance().saveContacts();
}
}
Controller.java:
package sample;
#FXML
private TableView<Contact> tableView;
#FXML
private BorderPane mainBorderPane;
private Contact item;
public Controller() {
}
#FXML
public TableView<Contact> getTableView() {
return tableView;
}
#FXML
public void initialize(){
loadContacts();
tableView.setOnMouseClicked((MouseEvent event) -> {
if (event.getClickCount() > 0) {
item = tableView.getSelectionModel().getSelectedItem(); // *** get selection from TableView ***
}
});
}
#FXML
public void handleExit(){
ContactData.getInstance().saveContacts();
Platform.exit();
}
public void saveContacts() {
ContactData.getInstance().saveContacts();
}
public void loadContacts() {
ContactData.getInstance().loadContacts();
tableView.setItems(ContactData.getInstance().getContacts());
}
public void deleteContact(){
ContactData.getInstance().deleteContact(item);
}
public void showAddContactDialog(ActionEvent event) throws IOException {
Dialog<ButtonType> dialog = new Dialog<>();
dialog.initOwner(mainBorderPane.getScene().getWindow());
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("addContact.fxml"));
try{
dialog.getDialogPane().setContent(fxmlLoader.load());
}catch(IOException e){
System.out.println("Couldn't load the dialog");
e.printStackTrace();
return;
}
Optional<ButtonType> result = dialog.showAndWait();
if(result.isPresent()){
Dialog controller = fxmlLoader.getController();
}
}
public void showEditContactDialog() throws Exception {
Dialog<ButtonType> dialog = new Dialog<>();
dialog.initOwner(mainBorderPane.getScene().getWindow());
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("editContact.fxml"));
EditContactController editController = fxmlLoader.<EditContactController>getController();
editController.setItem(item); // ****** trying to pass "item" but get NullPointerException *********
try{
dialog.getDialogPane().setContent(fxmlLoader.load());
} catch (IOException e) {
System.out.println("Couldn't load the dialog");
e.printStackTrace();
return;
}
Optional<ButtonType> result = dialog.showAndWait();
}
}
EditContactController.java
package sample;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import sample.datamodel.Contact;
public class EditContactController{
#FXML
private TextField fName;
#FXML
private TextField lName;
#FXML
private TextField pNumber;
#FXML
private TextArea nNotes;
#FXML
private javafx.scene.control.Button cancelButton;
#FXML
private Contact item;
public void setItem(Contact item) {
this.item = item;
}
#FXML
public void initialize(){
try {
fName.setText(item.getFirstName());
}catch(NullPointerException e) {
System.out.println("null point --> " + e.getMessage());
e.printStackTrace();
}
}
//#FXML
public void cancelButtonAction(){
// get a handle to the stage
Stage stage = (Stage) cancelButton.getScene().getWindow();
stage.close();
}
}
editContact.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.text.Font?>
<GridPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.EditContactController">
<HBox GridPane.columnSpan="2">
<Label text="Edit contact">
<font>
<Font name="System Bold" size="17.0" />
</font>
<padding>
<Insets bottom="10.0" left="10.0" />
</padding></Label>
</HBox>
<Label text="First Name" GridPane.columnIndex="0" GridPane.hgrow="ALWAYS" GridPane.rowIndex="1">
<GridPane.margin>
<Insets left="10.0" />
</GridPane.margin>
<padding>
<Insets bottom="5.0" />
</padding></Label>
<Label text="Last Name" GridPane.columnIndex="0" GridPane.rowIndex="2">
<GridPane.margin>
<Insets bottom="5.0" left="10.0" />
</GridPane.margin></Label>
<Label text="Phone number" GridPane.columnIndex="0" GridPane.rowIndex="3">
<GridPane.margin>
<Insets bottom="5.0" left="10.0" />
</GridPane.margin></Label>
<Label text="Notes" GridPane.columnIndex="0" GridPane.rowIndex="4">
<GridPane.margin>
<Insets bottom="5.0" left="10.0" />
</GridPane.margin></Label>
<TextField fx:id="fName" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="5.0" />
</GridPane.margin></TextField>
<TextField fx:id="lName" GridPane.columnIndex="1" GridPane.rowIndex="2">
<GridPane.margin>
<Insets bottom="5.0" />
</GridPane.margin></TextField>
<TextField fx:id="pNumber" GridPane.columnIndex="1" GridPane.rowIndex="3">
<GridPane.margin>
<Insets bottom="5.0" />
</GridPane.margin></TextField>
<TextArea fx:id="nNotes" GridPane.columnIndex="1" GridPane.rowIndex="4">
<GridPane.margin>
<Insets bottom="5.0" />
</GridPane.margin></TextArea>
<HBox alignment="TOP_RIGHT" spacing="5.0" GridPane.columnIndex="1" GridPane.rowIndex="5">
<Button text="Edit">
<opaqueInsets>
<Insets />
</opaqueInsets></Button>
<Button fx:id="cancelButton" cancelButton="true" onAction="#cancelButtonAction" text="Cancel" />
<opaqueInsets>
<Insets />
</opaqueInsets>
<GridPane.margin>
<Insets />
</GridPane.margin>
<padding>
<Insets bottom="5.0" left="5.0" right="5.0" />
</padding>
</HBox>
<columnConstraints>
<ColumnConstraints maxWidth="288.0" minWidth="22.0" prefWidth="129.0" />
<ColumnConstraints maxWidth="578.0" minWidth="312.0" prefWidth="471.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints />
<RowConstraints />
<RowConstraints />
<RowConstraints />
<RowConstraints />
<RowConstraints />
</rowConstraints>
<padding>
<Insets left="5.0" right="5.0" top="5.0" />
</padding>
<opaqueInsets>
<Insets />
</opaqueInsets>
</GridPane>
Stack:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8413)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:432)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
... 48 more
Caused by: java.lang.NullPointerException
at sample.Controller.showEditContactDialog(Controller.java:105)
... 58 more
Your controller class is specified in the FXML file, so the FXMLLoader cannot instantiate it until it reads that file. This means the controller is only created during the call to load(), and calling fxmlLoader.getController() prior to that will return null.
So you need to move the code that retrieves the controller and acts on it so that it is executed after you call load():
public void showEditContactDialog() throws Exception {
Dialog<ButtonType> dialog = new Dialog<>();
dialog.initOwner(mainBorderPane.getScene().getWindow());
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("editContact.fxml"));
try {
Parent dialogContent = fxmlLoader.load();
EditContactController editController = fxmlLoader.<EditContactController>getController();
editController.setItem(item);
dialog.getDialogPane().setContent(dialogContent);
} catch (IOException e) {
System.out.println("Couldn't load the dialog");
e.printStackTrace();
return;
}
Optional<ButtonType> result = dialog.showAndWait();
}
The initialize() method in the controller is also called during the call to FXMLLoader.load(). So, as a consequence of these changes, initialize() is now called before you call setItem(...) on the EditContactController. So you need to move the code that depends on the item from the initialize() method to the setItem() method:
public void setItem(Contact item) {
this.item = item;
fName.setText(item.getFirstName());
}
#FXML
public void initialize(){
}

where is the error??? showing "java.lang.reflect.InvocationTargetException"

Why this exception is happening ,I tried to fix it but seeing no solution
but, I find no clue to solve those exceptions
//main
package filebrowser;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
public class FileBrowser extends Application
{
#Override
public void start(Stage stage) throws Exception{
Parent root=FXMLLoader.load(getClass().getResource("fileExplorer.fxml"));
Scene scene=new Scene(root);
stage.setTitle("Windows File Explorer");
stage.getIcons().add(new
Image(ClassLoader.getSystemResourceAsStream("filebrowser/application-x-executable.png")));
stage.setScene(scene);
stage.show();
}
public static void main(String[] args){
launch(args);
}
}
/*controller class this is the main control class i think error should be there but could not figure out it yet.
package filebrowser;
import java.io.File;
import java.net.URL;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class FXMLcontroller{
#FXML
private ListView<String> listviewFiles;
#FXML
private TreeView<String> treeviewFileBrowse;
public void initialize() {
assert treeviewFileBrowse != null : "fx:id=\"treeviewFileBrowse\" was not injected: check your FXML file 'FileExplorer.fxml'.";
TreeItem<String> rootNode=new TreeItem<>("This PC",new ImageView(new Image(ClassLoader.getSystemResourceAsStream("filebrowser/computer.png"))));
Iterable<Path> rootDirectories=FileSystems.getDefault().getRootDirectories();
for(Path name:rootDirectories){
FilePathTreeItem treeNode=new FilePathTreeItem(new File(name.toString()));
rootNode.getChildren().add(treeNode);
}
rootNode.setExpanded(true);
this.treeviewFileBrowse.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
this.treeviewFileBrowse.setRoot(rootNode);
//this.listviewFiles.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
}
}
//file path tree class
package filebrowser;
import java.io.File;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.TreeItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class FilePathTreeItem extends TreeItem<String>{
public static Image folderCollapseImage=new Image(ClassLoader.getSystemResourceAsStream("filebrowser/folder.png"));
public static Image folderExpandImage=new Image(ClassLoader.getSystemResourceAsStream("filebrowser/folder-open.png"));
public static Image fileImage=new Image(ClassLoader.getSystemResourceAsStream("filebrowser/text-x-generic.png"));
private boolean isLeaf;
private boolean isFirstTimeChildren=true;
private boolean isFirstTimeLeaf=true;
private final File file;
public File getFile(){return(this.file);}
private final String absolutePath;
public String getAbsolutePath(){return(this.absolutePath);}
private final boolean isDirectory;
public boolean isDirectory(){return(this.isDirectory);}
public FilePathTreeItem(File file){
super(file.toString());
this.file=file;
this.absolutePath=file.getAbsolutePath();
this.isDirectory=file.isDirectory();
if(this.isDirectory){
this.setGraphic(new ImageView(folderCollapseImage));
//add event handlers
this.addEventHandler(TreeItem.branchCollapsedEvent(),new EventHandler(){
#Override
public void handle(Event e){
FilePathTreeItem source=(FilePathTreeItem)e.getSource();
if(!source.isExpanded()){
ImageView iv=(ImageView)source.getGraphic();
iv.setImage(folderCollapseImage);
}
}
} );
this.addEventHandler(TreeItem.branchExpandedEvent(),new EventHandler(){
#Override
public void handle(Event e){
FilePathTreeItem source=(FilePathTreeItem)e.getSource();
if(source.isExpanded()){
ImageView iv=(ImageView)source.getGraphic();
iv.setImage(folderExpandImage);
}
}
} );
}
else{
this.setGraphic(new ImageView(fileImage));
}
//set the value (which is what is displayed in the tree)
String fullPath=file.getAbsolutePath();
if(!fullPath.endsWith(File.separator)){
String value=file.toString();
int indexOf=value.lastIndexOf(File.separator);
if(indexOf>0){
this.setValue(value.substring(indexOf+1));
}else{
this.setValue(value);
}
}
}
#Override
public ObservableList<TreeItem<String>> getChildren(){
if(isFirstTimeChildren){
isFirstTimeChildren=false;
super.getChildren().setAll(buildChildren(this));
}
return(super.getChildren());
}
#Override
public boolean isLeaf(){
if(isFirstTimeLeaf){
isFirstTimeLeaf=false;
isLeaf=this.file.isFile();
}
return(isLeaf);
}
private ObservableList<FilePathTreeItem> buildChildren(FilePathTreeItem treeItem){
File f=treeItem.getFile();
if((f!=null)&&(f.isDirectory())){
File[] files=f.listFiles();
if (files!=null){
ObservableList<FilePathTreeItem> children=FXCollections.observableArrayList();
for(File childFile:files){
children.add(new FilePathTreeItem(childFile));
}
return(children);
}
}
return FXCollections.emptyObservableList();
}
}
//FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.*?><?import javafx.scene.effect.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane xmlns="http://javafx.com/javafx/8"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="filebrowser.FXMLcontroller">
<children>
<TreeView fx:id="treeviewFileBrowse" layoutX="2.0" layoutY="78.0"
prefHeight="304.0" prefWidth="171.0" />
<Button layoutX="14.0" layoutY="35.0" mnemonicParsing="false"
prefHeight="22.0" prefWidth="29.0" text="<" />
<MenuBar layoutY="2.0" prefHeight="25.0" prefWidth="600.0">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Home">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Share">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="View">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
</menus>
</MenuBar>
<Button layoutX="43.0" layoutY="35.0" mnemonicParsing="false"
prefHeight="22.0" prefWidth="29.0" text=">" />
<TextField layoutX="475.0" layoutY="35.0" prefHeight="25.0"
prefWidth="111.0" promptText="Search quick text" />
<TableView layoutX="179.0" layoutY="78.0" prefHeight="304.0"
prefWidth="417.0">
<columns>
<TableColumn prefWidth="50.0" text="Icon" />
<TableColumn prefWidth="144.0" text="Name" />
<TableColumn minWidth="0.0" prefWidth="106.0" text="Date Modified" />
<TableColumn minWidth="0.0" prefWidth="69.0" text="Size" />
<TableColumn minWidth="0.0" prefWidth="45.0" text="Type" />
</columns>
</TableView>
<TextField layoutX="102.0" layoutY="35.0" prefHeight="25.0"
prefWidth="365.0" promptText="Search Here" />
<AmbientLight color="CHARTREUSE" lightOn="true" />
<PointLight color="CHARTREUSE" lightOn="true" />
</children>
</AnchorPane>`
//output exception
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException: Location is required.
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3207)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at filebrowser.FileBrowser.start(FileBrowser.java:14)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Exception running application filebrowser.FileBrowser
Java Result: 1

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 TableView values Null

I am getting some error that I do not understand every time I try to run this program. The error seems to be triggered only when I have set these following lines BaseColorColumn.setCellValueFactory(new PropertyValueFactory<BaseColor, String>("BaseColor"));
and PriceColumn.setCellValueFactory(new PropertyValueFactory<BaseColor, Integer>("Price"));
I believe they're returning NULL but I am not sure why. I am basically just trying to fill in the table called CustomerTableView with data from BaseColor
//FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="supremeinkcalcmk2.MainController">
<left>
<VBox prefHeight="400.0" prefWidth="152.0" BorderPane.alignment="CENTER">
<children>
<TableView prefHeight="404.0" prefWidth="152.0">
<columns>
<TableColumn editable="false" prefWidth="75.0" sortable="false" text="Formla" />
<TableColumn editable="false" prefWidth="75.0" sortable="false" text="Price" />
</columns>
</TableView>
</children>
</VBox>
</left>
<right>
<VBox prefHeight="400.0" prefWidth="152.0" BorderPane.alignment="CENTER">
<children>
<ComboBox fx:id="ComboBoxSelectCustomer" prefWidth="150.0" promptText="Select Customer" />
<TableView fx:id="CustomerTableView" prefHeight="266.0" prefWidth="152.0">
<columns>
<TableColumn fx:id="BaseColor" prefWidth="75.0" text="Base Color" />
<TableColumn fx:id="Price" editable="false" prefWidth="75.0" sortable="false" text="Price" />
</columns>
</TableView>
<Button fx:id="ButtonSaveCustomer" mnemonicParsing="false" prefHeight="25.0" prefWidth="152.0" text="Save Customer" />
</children>
</VBox>
</right>
<center>
<Pane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<children>
<Label layoutX="103.0" layoutY="122.0" text="Pantone Number" />
<TextField layoutX="74.0" layoutY="139.0" />
<Label fx:id="PriceLabel" layoutX="132.0" layoutY="293.0" />
<Button fx:id="ButtonCalculate" layoutX="113.0" layoutY="200.0" mnemonicParsing="false" onAction="#CalculateButton" text="Calculate" />
<Label layoutX="131.0" layoutY="285.0" text="Label" />
</children>
</Pane>
</center>
</BorderPane>
//MainController.Java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package supremeinkcalcmk2;
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.ComboBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
/**
* FXML Controller class
*
* #author Archa
*/
public class MainController implements Initializable {
#FXML public ComboBox ComboBoxSelectCustomer;
#FXML private TableView<BaseColor> CustomerTableView;
#FXML private TableColumn<BaseColor, String> BaseColorColumn;
#FXML private TableColumn<BaseColor, Integer> PriceColumn;
//Customer TableView
ObservableList<BaseColor> data = FXCollections.observableArrayList(
new BaseColor("Yellow", 0),
new BaseColor("Green", 0),
new BaseColor("Blue", 0)
);
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
//CustomerTableView
BaseColorColumn.setCellValueFactory(new PropertyValueFactory<BaseColor, String>("BaseColor"));
PriceColumn.setCellValueFactory(new PropertyValueFactory<BaseColor, Integer>("Price"));
CustomerTableView.setItems(data);
}
public void CalculateButton(){
System.out.print("it is working!");
}
}
//BaseColor.Java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package supremeinkcalcmk2;
/**
*
* #author Arch
*/
public class BaseColor {
private String BaseColor;
private double Price;
public BaseColor(String BaseColor, double Price){
this.BaseColor = "";
this.Price = 0;
}
public String getBaseColor() {
return BaseColor;
}
public void setBaseColor(String BaseColor) {
this.BaseColor = BaseColor;
}
public double getPrice() {
return Price;
}
public void setPrice(double Price) {
this.Price = Price;
}
}
//Error log
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$152(LauncherImpl.java:182)
at com.sun.javafx.application.LauncherImpl$$Lambda$50/1343441044.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: javafx.fxml.LoadException:
file:/D:/Programming/SupremeInkCalcMk2/dist/run103801275/SupremeInkCalcMk2.jar!/supremeinkcalcmk2/Main.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2605)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2583)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2445)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3218)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3179)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3152)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3128)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3108)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3101)
at supremeinkcalcmk2.SupremeInkCalcMk2.start(SupremeInkCalcMk2.java:33)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$159(LauncherImpl.java:863)
at com.sun.javafx.application.LauncherImpl$$Lambda$53/726585699.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl$$Lambda$46/355629945.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(PlatformImpl.java:295)
at com.sun.javafx.application.PlatformImpl$$Lambda$48/1149823713.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(PlatformImpl.java:294)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/1915503092.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$145(WinApplication.java:101)
at com.sun.glass.ui.win.WinApplication$$Lambda$36/1963387170.run(Unknown Source)
... 1 more
Caused by: java.lang.NullPointerException
at supremeinkcalcmk2.MainController.initialize(MainController.java:52)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2552)
... 22 more
Exception running application supremeinkcalcmk2.SupremeInkCalcMk2
Java Result: 1
Your fx:ids do not match the field names:
<TableColumn fx:id="BaseColor" prefWidth="75.0" text="Base Color" />
<TableColumn fx:id="Price" editable="false" prefWidth="75.0" sortable="false" text="Price" />
but
#FXML private TableColumn<BaseColor, String> BaseColorColumn;
#FXML private TableColumn<BaseColor, Integer> PriceColumn;

Resources