NullPointerException when using #FXML after adding new Node to Scene - javafx

I am creating tabs dinamically. For that reason I created new FXML file, which is used for the new Tabs. I tried to add this Node (AnchorPane) to the scene. When I tried to call TextBox, Label, Button, etc of this AnchorPane, Eclipse throws nullponterException.
package mrpuppy.controller.cliente;
import java.io.IOException;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import mrpuppy.DTO.ApplicationContextDTO;
import mrpuppy.entity.Cliente;
import mrpuppy.entity.Mascota;
import mrpuppy.service.ClienteService;
#Controller
public class EditarClienteControllerImpl implements EditarClienteController
{
private Stage primaryStage;
private Scene scene;
private FXMLLoader loader;
private final String css = this.getClass().getResource("/css/editarCliente.css").toExternalForm();
#Autowired
private ClienteService clienteService;
#Autowired
private ListaClientesController listaClientesController;
private int intTabs=0;
private Tab[] openTabs;
#FXML
private TabPane tabPane;
#FXML
private Tab tabMascota;
#FXML
private TextField fieldNombreCliente;
#FXML
private TextField fieldApellidos;
#FXML
private TextField fieldDni;
#FXML
private TextField fieldTelMovil;
#FXML
private TextField fieldTelFijo;
#FXML
private TextField fieldDireccion;
#FXML
private TextField fieldCorreo;
#FXML
private ComboBox<String> comboMascota;
#FXML
private ComboBox<String> comboTamano;
#FXML
private TextField fieldNombreMascota;
#FXML
private RadioButton radioAlergiaSi;
#FXML
private RadioButton radioAlergiaNo;
#FXML
private TextField fieldRaza;
#FXML
private TextField fieldPeso;
#FXML
private ComboBox<String> comboSexo;
#FXML
private ComboBox<String> comboAgresividad;
#FXML
private TextArea areaObservaciones;
#FXML
private Button buttonCancelarEditarCliente;
#FXML
private Button buttonAceptarEditarCliente;
private ApplicationContextDTO applicationContextDTO;
#Override
public void openWindow(Cliente cliente)
{
try
{
primaryStage = new Stage();
primaryStage.setResizable(false);
loader = new FXMLLoader(getClass().getResource("/view/editarCliente.fxml"));
loader.setController(this); //Establecemos esta clase como "controller"
scene = loader.load();
scene.getStylesheets().add(css);
primaryStage.setScene(scene);
primaryStage.initModality(Modality.APPLICATION_MODAL);
primaryStage.show();
rellenarCamposCliente(cliente);
rellenarCamposMascota(cliente);
buttonCancelarEditarCliente.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
primaryStage.close();
}
});
buttonAceptarEditarCliente.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
cliente.setNombre(fieldNombreCliente.getText());
cliente.setApellidos(fieldApellidos.getText());
cliente.setDni(fieldDni.getText());
cliente.setTelefonoMovil(Integer.parseInt(fieldTelMovil.getText()));
cliente.setTelefonoFijo(Integer.parseInt(fieldTelFijo.getText()));
cliente.setDireccion(fieldDireccion.getText());
cliente.setCorreo(fieldCorreo.getText());
clienteService.actualizarCliente(cliente);
primaryStage.close();
}
});
}
catch(IOException ioe)
{
System.out.println(ioe.getMessage());
}
}
private void rellenarCamposCliente(Cliente cliente)
{
applicationContextDTO = new ApplicationContextDTO();
applicationContextDTO.setClienteService();
clienteService = applicationContextDTO.getClienteService();
fieldNombreCliente.setText(cliente.getNombre());
fieldApellidos.setText(cliente.getApellidos());
fieldDni.setText(cliente.getDni());
fieldTelMovil.setText(String.valueOf(cliente.getTelefonoMovil()));
fieldTelFijo.setText(String.valueOf(cliente.getTelefonoFijo()));
fieldDireccion.setText(cliente.getDireccion());
fieldCorreo.setText(cliente.getCorreo());
return;
}
private void rellenarCamposMascota(Cliente cliente)
{
try
{
AnchorPane anchorPane = new AnchorPane();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/mascotaTab.fxml"));
anchorPane.getChildren().add(loader.load());
Collection<Mascota> mascotas = cliente.getMascotas();
for(Mascota mascota : mascotas)
{
Tab newTab = new Tab();
FXMLLoader loader2 = new FXMLLoader(getClass().getResource("/view/mascotaTab.fxml"));
newTab.setContent(loader2.load());
tabPane.getTabs().add(newTab);
fieldNombreMascota.setText(mascota.getNombre());
fieldRaza.setText(mascota.getRaza());
comboSexo.setValue(mascota.getSexo());
fieldPeso.setText(String.valueOf(mascota.getPeso()));
comboTamano.setValue(mascota.getTamano());
comboAgresividad.setValue(mascota.getAgresividad());
areaObservaciones.setText(mascota.getObservaciones());
}
}
catch(IOException ioe)
{
System.out.println(ioe.getMessage());
}
}
}
This is the fxml file of the scene:
editarCliente.fxml
<Scene width="550" height="350" xmlns:fx="http://javafx.com/fxml">
<BorderPane id="root">
<top>
<TabPane fx:id="tabPane">
<tabs>
<Tab fx:id="tabCliente" text="Cliente" >
<content>
<AnchorPane fx:id="paneCliente">
<VBox fx:id="vBoxBloqueCliente">
<children>
<HBox fx:id="hBoxNombreApellidos">
<children>
<Label fx:id="labelNombre" text="Nombre:"/>
<TextField fx:id="fieldNombreCliente"/>
<Label fx:id="labelApellidos" text="Apellidos:"/>
<TextField fx:id="fieldApellidos"/>
</children>
</HBox>
<HBox fx:id="hBoxDniMovil">
<children>
<Label fx:id="labelDni" text="DNI:"/>
<TextField fx:id="fieldDni"/>
<Label fx:id="labelTelMovil" text="Teléfono Móvil:"/>
<TextField fx:id="fieldTelMovil"/>
</children>
</HBox>
<HBox fx:id="hBoxFijoDireccion">
<children>
<Label fx:id="labelTelFijo" text="Teléfono Fijo:
(opcional)"/>
<TextField fx:id="fieldTelFijo"/>
<Label fx:id="labelDireccion" text="Dirección:"/>
<TextField fx:id="fieldDireccion"/>
</children>
</HBox>
<HBox fx:id="hBoxCorreo">
<children>
<Label fx:id="labelCorreo" text="Correo:"/>
<TextField fx:id="fieldCorreo"/>
</children>
</HBox>
<HBox fx:id="hBoxBotonesCliente">
<children>
<Button fx:id="buttonCancelarEditarCliente" text="CANCELAR"/>
<Button fx:id="buttonAceptarEditarCliente" text="CONFIRMAR"/>
</children>
</HBox>
</children>
</VBox>
</AnchorPane>
</content>
</Tab>
</tabs>
</TabPane>
</top>
</BorderPane>
</Scene>
This is the fxml file of the new tabs:
mascotaTab.fxml
<AnchorPane fx:id="paneEditarMascota" xmlns:fx="http://javafx.com/fxml">
<VBox fx:id="vBoxBloqueEditarMascota">
<children>
<HBox fx:id="hBoxMascotaTamano">
<children>
<ComboBox fx:id="comboMascota">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="Perro" />
<String fx:value="Gato" />
</FXCollections>
</items>
<value>
<String fx:value="Seleccionar mascota" />
</value>
</ComboBox>
<ComboBox fx:id="comboTamano">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="Pequeño" />
<String fx:value="Mediano" />
<String fx:value="Grande" />
</FXCollections>
</items>
<value>
<String fx:value="Seleccionar tamaño" />
</value>
</ComboBox>
</children>
</HBox>
<HBox fx:id="hBoxNombreAlergia">
<fx:define>
<ToggleGroup fx:id="groupAlergia"/>
</fx:define>
<children>
<Label fx:id="labelNombreMascota" text="Nombre:"/>
<TextField fx:id="fieldNombreMascota"/>
<Label fx:id="labelAlergico" text="Alergico:"/>
<RadioButton fx:id="radioAlergiaSi" text="Si" toggleGroup="$groupAlergia"/>
<RadioButton fx:id="radioAlergiaNo" text="No" toggleGroup="$groupAlergia"/>
</children>
</HBox>
<HBox fx:id="hBoxRaza">
<children>
<Label fx:id="labelRaza" text="Raza:"/>
<TextField fx:id="fieldRaza"/>
<Label fx:id="labelPeso" text="Peso:"/>
<TextField fx:id="fieldPeso"/>
</children>
</HBox>
<HBox fx:id="hBoxSexoAgresividad">
<children>
<ComboBox fx:id="comboSexo">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="Macho" />
<String fx:value="Hembra" />
</FXCollections>
</items>
<value>
<String fx:value="Seleccionar sexo" />
</value>
</ComboBox>
<ComboBox fx:id="comboAgresividad">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="Tranquilo" />
<String fx:value="Nervioso" />
<String fx:value="Agresivo" />
</FXCollections>
</items>
<value>
<String fx:value="Seleccionar agresividad" />
</value>
</ComboBox>
</children>
</HBox>
<HBox fx:id="hBoxObservaciones">
<TextArea fx:id="areaObservaciones"/>
</HBox>
<HBox fx:id="hBoxBotonesAnadirMascota">
<Button fx:id="buttonVolverAnadirMascota"/>
<Button fx:id="buttonHomeAnadirMascota"/>
<Button fx:id="buttonAnadirMascota"/>
</HBox>
</children>
</VBox>
</AnchorPane>
Edit: NullPointer exception is in "rellenarMascota" method. Any control I include in the second fxml file throws NullPointerException, but any control I include in the first fxml file doesn't throw that exception. For example the NPE is throwing at fieldNombreMascota.setText(mascota.getNombre()); in "rellenarMascota" method.

Related

JavaFX FXML Show Updated TableView

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>

JavaFX popup not working

I’m trying to learn how to get a JavaFX popup window to open from a menu item click. I finally got a new window to open but I can’t seem to make it modal. Here's my code:
Scene 1 FXML:
<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sceneswitchtest.Scene_1Controller">
<children>
<Button fx:id="button" layoutX="126" layoutY="90" onAction="#handleButtonAction" text="Click Me!" />
<Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" />
<MenuBar fx:id="menuBar" layoutX="40.0" layoutY="27.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
<MenuItem fx:id="MenuItemOpenScene2" mnemonicParsing="false" onAction="#OpenScene2" text="Open Scene 2" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
</children>
</AnchorPane>
Popup FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sceneswitchtest.Scene_2Controller">
</AnchorPane>
Scene 1 controller:
package sceneswitchtest;
import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class Scene_1Controller {
#FXML
private Button button;
#FXML
private Label label;
#FXML
private MenuBar menuBar;
#FXML
private MenuItem MenuItemOpenScene2;
#FXML
void OpenScene2(ActionEvent event) throws IOException {
Stage appStage = (Stage) ((Node) menuBar).getScene().getWindow();
Parent settingsParent = FXMLLoader.load(this.getClass().getResource("Scene_2.fxml"));
Scene settingsScene = new Scene(settingsParent);
appStage.setScene(settingsScene);
// appStage.initModality(Modality.WINDOW_MODAL);
// appStage.initOwner(menuBar.getScene().getWindow());
appStage.show();
}
#FXML
void handleButtonAction(ActionEvent event) throws IOException {
}
}
Note: In the above code, the lines commented out failed as well as he use of Modality.APPLICATION_MODAL
Scene 2 (popup) controller:
package sceneswitchtest;
public class Scene_2Controller {
}
main method:
package sceneswitchtest;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* #author eric
*/
public class SceneSwitchTest extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Scene_1.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 the code changes I made in order to get the popup to work.
#FXML
void OpenScene2(ActionEvent event) throws IOException {
Parent settingsParent = FXMLLoader.load(this.getClass().getResource("/sceneswitchtest/Scene_2.fxml"));
Scene settingsScene = new Scene(settingsParent);
Stage popup = new Stage();
popup.setScene(settingsScene);
popup.initModality(Modality.WINDOW_MODAL);
popup.initOwner(menuBar.getScene().getWindow());
popup.show();
}
I would like to thank MBec for pointing me in the right direction.

JavaFX Adding Rows to TableView on Different Page

Okay, I've been working through some issues with this program and I think I've finally gotten it to a point where I understand what is wrong. I'm trying to follow this tutorial a bit: http://docs.oracle.com/javafx/2/fxml_get_started/fxml_tutorial_intermediate.htm But my program has the add a row on a different FXML page than the Table View is on. I think the program is having trouble connecting the two. I've looked in to trying to find ways to make them talk to each other (put everything in one Controller and it didn't like it, tried passing the controller through the class and that didn't work {might have done it wrong though}). My program also has Integers and Doubles in it which are not covered in that tutorial so I've tried to figure those out on my own (probably better ways of doing it than I did).
But right now I'm just focused on figuring out why it keeps thinking
data = partTable.getItems();
Is null (line 77 in AddPartController). Any help or other FXML/JavaFX tutorials would be greatly appreciated (though I've already looked through a lot of them).
FXMLDocument.fxml (main page)
<?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 text="Part ID">
<cellValueFactory>
<PropertyValueFactory property="id" />
</cellValueFactory>
</TableColumn>
<TableColumn fx:id="nameColumn" text="Part Name">
<cellValueFactory>
<PropertyValueFactory property="name" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Inventory Level">
<cellValueFactory>
<PropertyValueFactory property="instock" />
</cellValueFactory>
</TableColumn>
<TableColumn text="Price/Cost per Unit">
<cellValueFactory>
<PropertyValueFactory property="price" />
</cellValueFactory>
</TableColumn>
</columns>
<items>
<FXCollections fx:factory="observableArrayList">
<Inhouse name="Part 1" price="5.00" instock="5" max="10" min="1" />
<Inhouse name="Part 2" price="7.00" instock="2" max="11" min="2" />
</FXCollections>
</items>
<sortOrder>
<fx:reference source="nameColumn" />
</sortOrder>
</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>
FXMLDocumentController
/*
* 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 ims;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
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.Label;
import javafx.stage.Stage;
/**
*
* #author chelseacamper
*/
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
#FXML
private void addPart(ActionEvent event) throws IOException {
Parent add_part_parent = FXMLLoader.load(getClass().getResource("addPart.fxml"));
Scene add_part_scene = new Scene(add_part_parent);
add_part_scene.getStylesheets().add("style.css");
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(add_part_scene);
app_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) {
// TODO
}
}
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">
<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" />
</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" text="Save" />
<Button onAction="#backToMain" text="Cancel" />
</HBox>
</HBox>
</children>
</VBox>
</center>
</BorderPane>
AddPartController
/*
* 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 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.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<Inhouse> partTable;
#FXML
private TextField partNameField;
#FXML
private TextField partInstockField;
#FXML
private TextField partPriceField;
#FXML
private TextField partMaxField;
#FXML
private TextField partMinField;
/**
* 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){
ObservableList<Inhouse> data;
data = partTable.getItems();
data.add(new Inhouse(partNameField.getText(),
Integer.parseInt(partInstockField.getText()),
Double.parseDouble(partPriceField.getText()),
Integer.parseInt(partMaxField.getText()),
Integer.parseInt(partMinField.getText()),
Integer.parseInt(inhouseTextField.getText())
// Integer.parseInt(outsourcedTextField.getText())
));
partNameField.setText("");
partInstockField.setText(String.valueOf(partInstockField));
partPriceField.setText(String.valueOf(partPriceField));
partMaxField.setText(String.valueOf(partMaxField));
partMinField.setText(String.valueOf(partMinField));
inhouseTextField.setText(String.valueOf(inhouseTextField));
// outsourcedTextField.setText(String.valueOf(outsourcedTextField));
}
#FXML
private void backToMain(ActionEvent event) throws IOException {
Parent add_main_parent = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene add_main_scene = new Scene(add_main_parent);
add_main_scene.getStylesheets().add("style.css");
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(add_main_scene);
app_stage.show();
}
}
Errors that you get when you click add and then Save (don't even have to enter stuff)
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1770)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1653)
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:8390)
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:3758)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3486)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2495)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:350)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$350(GlassViewEventHandler.java:385)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$294/109927940.get(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:404)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:384)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:927)
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:497)
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:497)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1765)
... 46 more
Caused by: java.lang.NullPointerException
at ims.AddPartController.addInhouse(AddPartController.java:77)
... 56 more
The is no element in addPart.fxml with fx:id="partTable". Consequently partTable is null, and
partTable.getItems();
throws a null pointer exception.
You need to inject partTable into the controller for the FXML in which it is defined:
public class FXMLDocumentController implements Initializable {
#FXML
private Label label;
#FXML
private TableView<Inhouse> partTable ;
// ...
}
The AddPartController only needs access to the list of items associated with the table, so you can define a field for it, and a method for initializing it:
public class AddPartController implements Initializable {
// ...
private ObservableList<Inhouse> tableItems ;
public void setTableItems(ObservableList<Inhouse> tableItems) {
this.tableItems = tableItems ;
}
// ...
}
Then set the items when you load addPart.fxml:
#FXML
private void addPart(ActionEvent event) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("addPart.fxml"));
Parent add_part_parent = loader.load();
AddPartController addPartController = loader.getController();
addPartController.setTableItems(partTable.getItems());
Scene add_part_scene = new Scene(add_part_parent);
add_part_scene.getStylesheets().add("style.css");
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(add_part_scene);
app_stage.show();
}
and then of course you just need
#FXML
public void addInhouse(ActionEvent event){
tableItems.add(new Inhouse(partNameField.getText(),
Integer.parseInt(partInstockField.getText()),
Double.parseDouble(partPriceField.getText()),
Integer.parseInt(partMaxField.getText()),
Integer.parseInt(partMinField.getText()),
Integer.parseInt(inhouseTextField.getText())
// Integer.parseInt(outsourcedTextField.getText())
));
}
(FWIW I have no idea what
partInstockField.setText(String.valueOf(partInstockField));
etc etc is supposed to do.)

Reference Labels in Controller

I am trying to create a simple ui using fxml in javafx. I am trying to reference Labels that I have created in my .fxml file in my Controller class. But for some reason I can see an error when I go over the fxml tag where fx:id is given. It says Cannot set javafx.scene.control.Label to field 'leaders'.But it works fine for the ImageView. The code is as follows:
customcontrol.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.canvas.*?>
<?import javafx.scene.text.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<fx:root prefHeight="800.0" prefWidth="1005.0" type="javafx.scene.layout.VBox" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
<BorderPane prefHeight="800.0" prefWidth="1005.0">
<top>
<MenuBar BorderPane.alignment="CENTER">
<menus>
<Menu mnemonicParsing="false" text="About">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
</menus>
</MenuBar>
</top>
<left>
<ListView fx:id="mylist" minHeight="765.0" minWidth="250.0" prefHeight="771.0" prefWidth="250.0" BorderPane.alignment="CENTER_LEFT" />
</left>
<center>
<ScrollPane hbarPolicy="NEVER" prefViewportHeight="771.0" prefViewportWidth="750.0" vbarPolicy="ALWAYS">
<content>
<AnchorPane prefHeight="850.0" prefWidth="750.0" BorderPane.alignment="CENTER">
<children>
<ImageView fx:id="icon" fitHeight="200.0" fitWidth="150.0" layoutX="14.0" layoutY="14.0" pickOnBounds="true" preserveRatio="true" />
<ImageView fx:id="leader" fitHeight="200.0" fitWidth="150.0" layoutX="586.0" layoutY="14.0" pickOnBounds="true" preserveRatio="true" />
<Label fx:id="title" layoutX="231.0" layoutY="88.0" text="Punjab -2017" textAlignment="CENTER">
<font>
<Font name="American Typewriter Bold" size="43.0" />
</font>
</Label>
<Label fx:id="overview" layoutX="15.0" layoutY="283.0" text="Party Overview">
<font>
<Font name="AppleGothic Regular" size="23.0" />
</font>
</Label>
<Separator layoutX="15.0" layoutY="316.0" prefHeight="3.0" prefWidth="689.0" AnchorPane.bottomAnchor="1181.0" AnchorPane.leftAnchor="15.0" AnchorPane.rightAnchor="46.0" AnchorPane.topAnchor="316.0">
<opaqueInsets>
<Insets />
</opaqueInsets>
</Separator>
<Label fx:id="overtext" layoutX="17.0" layoutY="336.0" prefHeight="172.0" prefWidth="686.0" text="Label">
<font>
<Font name="Calibri Light" size="15.0" />
</font>
</Label>
<Label fx:id="prediction" layoutX="19.0" layoutY="497.0" text="Election Prediction">
<font>
<Font name="AppleGothic Regular" size="23.0" />
</font>
</Label>
<Label fx:id="predictext" layoutX="21.0" layoutY="547.0" prefHeight="172.0" prefWidth="686.0" text="Label">
<font>
<Font name="Calibri Light" size="15.0" />
</font>
</Label>
<Separator layoutX="19.0" layoutY="530.0" prefHeight="3.0" prefWidth="689.0">
<opaqueInsets>
<Insets />
</opaqueInsets>
</Separator>
<Label fx:id="leaders" layoutX="19.0" layoutY="719.0" text="Major Leaders">
<font>
<Font name="AppleGothic Regular" size="23.0" />
</font>
</Label>
<Separator layoutX="19.0" layoutY="752.0" prefHeight="3.0" prefWidth="689.0">
<opaqueInsets>
<Insets />
</opaqueInsets>
</Separator>
<Label layoutX="21.0" layoutY="769.0" prefHeight="172.0" prefWidth="686.0" text="Label" fx:id="leaderstext">
<font>
<Font name="Calibri Light" size="15.0" />
</font>
</Label>
</children>
</AnchorPane>
</content>
</ScrollPane>
</center>
</BorderPane>
</children>
</fx:root>
CustomControl.java
package sample;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
/**
* Sample custom control hosting a text field and a button.
*/
public class CustomControl extends VBox {
#FXML
private ListView mylist;
#FXML
private ImageView icon;
#FXML
private ImageView leader;
#FXML
private Label overview;
#FXML
private Label overtext;
#FXML
private Label prediction;
#FXML
private Label predictext;
#FXML
private Label leaders;
#FXML
private Label leaderstext;
public CustomControl() {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("custom_control.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
public void setList(){
mylist.setItems(FXCollections.observableArrayList("Home","BJP","Congress","AAP"));
}
public void setOverview(String txt) {
overview.setText(txt);
}
public void setOverviewtext(String txt){
overtext.setText(txt);
}
public void setLeader(String data){
File file =new File(data);
Image image = new Image(file.toURI().toString());
leader.setImage(image);
}
public void setIcon(String data){
File file =new File(data);
Image image = new Image(file.toURI().toString());
icon.setImage(image);
}
public void setPrediction(String txt){
prediction.setText(txt);
}
public void setPredictext(String txt){
predictext.setText(txt);
}
public void setLeaders(String txt){
leaders.setText(txt);
}
public void setLeaderstext(String txt){
leaderstext.setText(txt);
}
}
Main.java
package sample;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage stage) throws Exception {
CustomControl customControl = new CustomControl();
// customControl.setText("Hello!");
customControl.setList();
customControl.setIcon("/Users/Arun/Dropbox/Camera Saves/camera uploads/2015-04-02 16.23.11.jpg");
customControl.setLeader("/Users/Arun/Dropbox/Camera Saves/camera uploads/2015-04-02 16.23.11.jpg");
stage.setScene(new Scene(customControl));
stage.setTitle("Custom Control");
stage.setWidth(1017);
stage.setHeight(800);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
A million thanks in advance....
You have the wrong imports. Remove import java.awt.*; and add the correct imports for the JavaFX controls (import javafx.scene.control.Label;, etc)

trying to display objects on JAVAFX table and i am getting java.lang.NullPointerException

i am having issue with lines 112/113/114 the program will compile without them,
am trying to get the the data from (ObservableList database) and display it on the table, i try to keep the variables as date,double. changed them to SimpleDoubleProperty, SimpleObjectProperty.
this is the exception am getting
at com.sun.glass.ui.win.WinApplication.lambda$null$145(Unknown
Source) at
com.sun.glass.ui.win.WinApplication$$Lambda$36/2117255219.run(Unknown
Source) ... 1 more Caused by: java.lang.NullPointerException at
org.xcellcomm.Controller.initialize(Controller.java:103) ... 23 more
Exception running application org.xcellcomm.Start
package org.xcellcomm;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
public class Controller implements Initializable {
private final ObservableList<Mrc> data =
FXCollections.observableArrayList();
Date date;
ArrayList<Mrc> dailyMRC;
final static int VALUEBUNDLE = 5;
final static int PHP = 6;
final static int BLOCKIT = 1;
final static int RHAPSODY = 10;
final static int WORLDCALLING = 5;
final static int LOOKOUT = 3;
#FXML
private CheckBox checkboxFeatureLookout;
#FXML
private RadioButton plan40Radio;
#FXML
private CheckBox checkboxBlockIt;
#FXML
private CheckBox checkboxFeatureValueBundle;
#FXML
private TextField textfeildTodayGoal;
#FXML
private Button buttonAddActivation;
#FXML
private CheckBox checkboxFeatureRhpsody;
#FXML
private CheckBox checkboxFeatureWorldCalling;
#FXML
private RadioButton plan50Radio;
#FXML
private CheckBox checkboxFeaturePhp;
#FXML
private RadioButton plan60Radio;
#FXML
private TextField textfeildTodayActivations;
#FXML
private TableView<Plana> dailyActivationTable;
#FXML
private TableColumn<Plana, Date> dailyActivationTimeColon;
#FXML
private TableColumn<Plana, Double> dailyActivationPlanColon;
private final ObservableList<Plana> database =
FXCollections.observableArrayList();
#Override
public void initialize(URL location, ResourceBundle resources) {
dailyActivationPlanColon = new TableColumn<Controller.Plana, Double>();
dailyActivationTimeColon = new TableColumn<Controller.Plana, Date>();
dailyActivationTable.getColumns().addAll(dailyActivationPlanColon,dailyActivationTimeColon);
dailyMRC = new ArrayList<>();
ToggleGroup group = new ToggleGroup();
plan40Radio.setToggleGroup(group);
plan50Radio.setToggleGroup(group);
plan60Radio.setToggleGroup(group);
dailyActivationPlanColon.setCellValueFactory(new PropertyValueFactory<Plana, Double>("PlanProperty"));
dailyActivationTimeColon.setCellValueFactory(new PropertyValueFactory<Plana,Date>("dateProperty"));
dailyActivationTable.setItems(database);
}
//Getting input from the GUI and Calculate the MRC Constructor
private int newActivationCalculater(){
int mrc=0;
if(plan40Radio.isSelected())mrc=+40;
if(plan50Radio.isSelected())mrc=+50;
if(plan60Radio.isSelected())mrc=+60;
if(checkboxBlockIt.isSelected())mrc=+BLOCKIT;
if(checkboxFeatureLookout.isSelected())mrc=+LOOKOUT;
if(checkboxFeaturePhp.isSelected())mrc=+PHP;
if(checkboxFeatureRhpsody.isSelected())mrc=+RHAPSODY;
if(checkboxFeatureValueBundle.isSelected())mrc=+VALUEBUNDLE;
if(checkboxFeatureWorldCalling.isSelected())mrc=+WORLDCALLING;
return mrc;
}
//Getting the Current time for the mrc constructor
private Date currentTime(){
Date date = new Date();
return date;
}
public void buttonAddActivationPressed(){
if(plan40Radio.isSelected()||plan50Radio.isSelected()||plan60Radio.isSelected()){
double mrc = (double)newActivationCalculater();
Date date = currentTime();
//Mrc newactivation = ;
unselectAllItem();
database.add(new Plana((int)mrc, date));
todayactivationRefresh();
}//if end
else{//if user did not select plan
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("Warning!");
alert.setHeaderText("Something wrong:)");
alert.setContentText("You didn't select a Plan");
alert.showAndWait();}
}
void todayactivationRefresh(){
String todayactivation=dailyMRC.size()+"";
textfeildTodayActivations.setText(todayactivation);
}
void unselectAllItem(){
plan40Radio.setSelected(false);
plan50Radio.setSelected(false);
plan60Radio.setSelected(false);
checkboxBlockIt.setSelected(false);
checkboxFeatureLookout.setSelected(false);
checkboxFeaturePhp.setSelected(false);
checkboxFeatureValueBundle.setSelected(false);
checkboxFeatureWorldCalling.setSelected(false);
checkboxFeatureRhpsody.setSelected(false);
}
public class Plana {// its might not work because it is it's not public
// private final SimpleStringProperty dateStringProperty;
private final SimpleDoubleProperty PlanProperty;
private final SimpleObjectProperty<Date> dateProperty;
private Plana( double gPlan, Date gDate) {
// this.dateStringProperty = new SimpleStringProperty(gStringDate);
this.PlanProperty = new SimpleDoubleProperty(gPlan);
this.dateProperty = new SimpleObjectProperty<Date>(gDate);
}
/**
* #return the dateStringProperty
*/
// public SimpleStringProperty getDateStringProperty() {
// return dateStringProperty;
//}
/**
* #return the planProperty
*/
public SimpleDoubleProperty getPlanProperty() {
return PlanProperty;
}
/**
* #return the dateProperty
*/
public SimpleObjectProperty<Date> getDateProperty() {
return dateProperty;
}
}
}
and here is the startclass:
package org.xcellcomm;
import java.util.Date;
import javafx.application.Application;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
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.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class Start extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("mainMrc.fxml"));
Scene scene = new Scene(root);
stage.setTitle("MRC Monitor");
stage.setScene(scene);
stage.show();
}
public static void main(String []args){
launch(args);
}
}
mainMrc.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.chart.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.VBox?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.xcellcomm.Controller">
<center>
<VBox prefHeight="200.0" prefWidth="100.0" BorderPane.alignment="CENTER">
<children>
<Label text="Add New Activation :">
<VBox.margin>
<Insets />
</VBox.margin>
</Label>
<HBox prefHeight="100.0" prefWidth="200.0">
<children>
<HBox prefHeight="90.0" prefWidth="200.0">
<children>
<VBox prefHeight="200.0" prefWidth="100.0">
<children>
<Label text="Select Plan Rate :" />
<RadioButton fx:id="plan40Radio" mnemonicParsing="false" text="40 or less Plan" />
<RadioButton fx:id="plan50Radio" mnemonicParsing="false" text="50 Plan" />
<RadioButton fx:id="plan60Radio" mnemonicParsing="false" text="60 Plan" />
<Region prefHeight="16.0" prefWidth="100.0" />
<Button fx:id="buttonAddActivation" mnemonicParsing="false" onAction="#buttonAddActivationPressed" text="Add Activation" />
</children>
</VBox>
</children>
</HBox>
<VBox prefHeight="102.0" prefWidth="163.0">
<children>
<Label text="Added Features :" />
<CheckBox fx:id="checkboxFeaturePhp" layoutX="10.0" layoutY="27.0" mnemonicParsing="false" text="PHP" />
<CheckBox fx:id="checkboxBlockIt" mnemonicParsing="false" text="Block it" />
<CheckBox fx:id="checkboxFeatureValueBundle" mnemonicParsing="false" text="Value Bundle" />
</children>
</VBox>
<VBox prefHeight="200.0" prefWidth="100.0">
<children>
<Label text=" " />
<CheckBox fx:id="checkboxFeatureLookout" mnemonicParsing="false" text="Lookout MS" />
<CheckBox fx:id="checkboxFeatureRhpsody" mnemonicParsing="false" text="Rhapsody" />
<CheckBox fx:id="checkboxFeatureWorldCalling" mnemonicParsing="false" text="World Calling" />
</children>
</VBox>
</children>
</HBox>
<Region prefHeight="23.0" prefWidth="600.0" />
<HBox prefHeight="131.0" prefWidth="580.0">
<children>
<TableView prefHeight="100.0" prefWidth="263.0">
<columns>
<TableColumn prefWidth="109.0" text="Time" />
<TableColumn prefWidth="82.0" text="Plan" />
</columns>
<HBox.margin>
<Insets left="10.0" />
</HBox.margin>
</TableView>
<Region prefHeight="200.0" prefWidth="200.0" HBox.hgrow="ALWAYS" />
<TableView prefHeight="100.0" prefWidth="309.0">
<columns>
<TableColumn prefWidth="147.0" text="Date" />
<TableColumn prefWidth="90.0" text="MRC" />
</columns>
<HBox.margin>
<Insets right="10.0" />
</HBox.margin>
</TableView>
</children>
</HBox>
<Region prefHeight="29.0" prefWidth="580.0" />
<HBox prefHeight="100.0" prefWidth="200.0">
<children>
<VBox prefHeight="150.0" prefWidth="218.0">
<children>
<Label text="Today Activations" />
<TextField fx:id="textfeildTodayActivations" editable="false" maxWidth="100.0" prefHeight="39.0" prefWidth="100.0" promptText="Activations">
<font>
<Font size="18.0" />
</font>
</TextField>
<Label text="Today Goal" />
<TextField fx:id="textfeildTodayGoal" editable="false" maxWidth="100.0" prefHeight="39.0" prefWidth="100.0" promptText="Goal">
<font>
<Font size="18.0" />
</font>
</TextField>
<Label text="Current Process" />
<ProgressBar prefWidth="200.0" progress="0.0" />
</children>
</VBox>
<Region prefHeight="150.0" prefWidth="80.0" HBox.hgrow="ALWAYS" />
<LineChart prefHeight="150.0" prefWidth="281.0">
<xAxis>
<CategoryAxis side="BOTTOM" />
</xAxis>
<yAxis>
<NumberAxis side="LEFT" />
</yAxis>
</LineChart>
</children>
</HBox>
</children>
<BorderPane.margin>
<Insets left="10.0" right="10.0" />
</BorderPane.margin>
</VBox>
</center>
<top>
<MenuBar BorderPane.alignment="CENTER">
<menus>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" text="Close" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Edit">
<items>
<MenuItem mnemonicParsing="false" text="Delete" />
</items>
</Menu>
<Menu mnemonicParsing="false" text="Help">
<items>
<MenuItem mnemonicParsing="false" text="About" />
</items>
</Menu>
</menus>
</MenuBar>
</top>
</BorderPane>
Your tableView in the FXML file doesn't have and id, you have <TableView prefHeight="100.0" prefWidth="263.0">and it should have assign an id as you have in yours checkboxs,radiobuttons,etc.

Resources