NullPointerException in Listener class - pointers

Basically, I currently have this GUI:
What it's supposed to do is add all the highlighted items on the left scroll pane to the right scroll pane. However, whenever I press the "Add" button, I get a NullPointerException. The error happens in the ColumnMainPanel class under AddListener's actionPerformed when the allColsPanel.getList().getSelectedValuesList() gets executed.
My code looks like this:
In the main frame:
ColumnMainPanel columnsPanel = new ColumnMainPanel(allColumns);
frame.setContentPane(columnsPanel);
ColumnMainPanel:
public class ColumnMainPanel extends JPanel {
private AllColumnsPanel allColsPanel;
private SelectedColumnsPanel selColsPanel;
private CentralButtonsPane buttonPane;
public ColumnMainPanel() {
allColsPanel = null;
selColsPanel = null;
buttonPane = null;
}
public ColumnMainPanel(String[] allColumns) {
super(new BorderLayout());
this.dbe = d;
setSize(250, 700);
allColsPanel = new AllColumnsPanel(allColumns);
selColsPanel = new SelectedColumnsPanel(allColumns.length);
buttonPane = new CentralButtonsPane();
add(allColsPanel, BorderLayout.WEST);
add(buttonPane, BorderLayout.CENTER);
add(selColsPanel, BorderLayout.EAST);
}
class AddListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
//int index = list.getSelectedIndex();
String[] columnsSelected;
// This next line is where I get the error:
List<String> selectedValues = allColsPanel.getList().getSelectedValuesList();
columnsSelected = new String[selectedValues.size()];
columnsSelected = (selectedValues).toArray(columnsSelected);
selColsPanel.addToList(columnsSelected);
}
}
//add RemoveListener and ExportListener here
}
AllColumnsPanel:
public class AllColumnsPanel extends ColumnMainPanel implements ListSelectionListener {
private JList<String> list;
private DefaultListModel<String> listModel;
private int numListItems;
public AllColumnsPanel(String[] allColumns) {
setSize(300, 300);
this.numListItems = allColumns.length;
listModel = createListModel(allColumns);
list = createList(listModel);
JScrollPane listScrollPane = new JScrollPane(list);
listScrollPane.setPreferredSize(new Dimension(300, 300));
add(listScrollPane);
}
public DefaultListModel<String> createListModel(String[] cols) {
DefaultListModel<String> result = new DefaultListModel<String>();
for(int i = 0; i < cols.length; i ++) {
result.addElement(cols[i]);
}
return result;
}
public JList<String> createList(DefaultListModel<String> listModel) {
JList<String> result = new JList<String>(listModel);
result.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
result.setSelectedIndex(0);
result.addListSelectionListener(this);
result.setVisibleRowCount(5);
return result;
}
public JList<String> getList() {
return list;
}
public boolean isEmpty() {
return numListItems < 1;
}
}
CentralButtonsPane:
public class CentralButtonsPane extends ColumnMainPanel {
private static final String addString = "Add";
private static final String removeString = "Remove";
private static final String exportString = "Export";
public CentralButtonsPane() {
setLayout((new BoxLayout(this, BoxLayout.Y_AXIS)));
setSize(50, 40);
add(createAddButton());
add(createRemoveButton());
add(createExportButton());
}
public JButton createAddButton() {
JButton result = new JButton(addString);
result.setActionCommand(addString);
result.setSize(50, 20);
result.setAlignmentX(Component.CENTER_ALIGNMENT);
result.addActionListener(new AddListener());
return result;
}
}
I checked the allColsPanel right after I initialize it in the ColumnMainPanel constructor and it's not null. However, when I checked if allColsPanel, under the AddListener, is null, it returns true. What am I missing here? What am I doing wrong?
Here is the error I get:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at mhhls.him.dbtoexcelgui.main.ColumnMainPanel$AddListener.actionPerformed(ColumnMainPanel.java:53)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

Related

Unsupported Operation Exception Java.Sql.Date [duplicate]

This question already has an answer here:
Convert between LocalDate and sql.Date [duplicate]
(1 answer)
Closed 4 years ago.
hello i need to display a date column in a tableview; in the database I declare the field fecha_nacimiento as date , i used a datepicker to insert that data into the database, so far its Ok with that operation so the next step was formatting the tableview cell to display the date data correctly, with the help of this site i did that, but when i need to retrieve the date data from the database i am getting an error, something like this:
Caused by: java.lang.UnsupportedOperationException
at java.sql.Date.toInstant(Unknown Source)
this is some of my controller code
public void initialize(URL arg0, ResourceBundle arg1) {
clienteid.setCellValueFactory(new PropertyValueFactory <Persona, Integer>("id_cliente"));
nombrescol.setCellValueFactory(new PropertyValueFactory <Persona, String>("nombres"));
apellidoscol.setCellValueFactory(new PropertyValueFactory <Persona, String>("apellidos"));
//fechacli.setCellValueFactory(new PropertyValueFactory <Persona, LocalDate>("fechacliente"));//
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
fechacli.setCellFactory(column -> {
return new TableCell<Persona, LocalDate>() {
#Override
protected void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
} else {
setText(formatter.format(item));
}
}
};
});
seleccionaregistros();
seleccionanombre();
seleccionapellido();
}
public void seleccionaregistros() {
ObservableList <Persona> data =FXCollections.observableArrayList();
Connection conn=null;{
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
Statement mostrar=conn.createStatement();
ResultSet rs;
rs= mostrar.executeQuery("select * from cliente");
while ( rs.next() )
{
data.add(new Persona(
rs.getString("nombre"),
rs.getString("apellido"),
rs.getInt("id"),
rs.getDate(4).toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
);
tablacliente.setItems(data);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
this is my persona class code
package application;
import java.time.LocalDate;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Persona {
private StringProperty nombres;
private StringProperty apellidos;
private IntegerProperty id_cliente;
private ObjectProperty <LocalDate>fechacliente;
public Persona (String nombres, String apellidos, Integer id_cliente, LocalDate fechacliente) {
this.nombres= new SimpleStringProperty (nombres);
this.apellidos= new SimpleStringProperty ( apellidos);
this.id_cliente=new SimpleIntegerProperty (id_cliente);
this.fechacliente= new SimpleObjectProperty<>(fechacliente);
}
public LocalDate getFechaCliente() {
return fechacliente.get();
}
public void setFechaCliente(LocalDate fechacliente) {
this.fechacliente = new SimpleObjectProperty<>(fechacliente);
}
public ObjectProperty<LocalDate> fechaClienteProperty() {
return fechacliente;
}
public String getNombres() {
return nombres.get();
}
public void setNombres(String nombres) {
this.nombres=new SimpleStringProperty (nombres);
}
public String getApellidos() {
return apellidos.get();
}
public void setApellidos(String apellidos) {
this.apellidos=new SimpleStringProperty ( apellidos);
}
public Integer getId_cliente() {
return id_cliente.get();
}
public void setid_cliente(Integer id_cliente) {
this.id_cliente=new SimpleIntegerProperty (id_cliente);
}
}
id have been reading, and i found that can't truncate or pass the data beetween Localdate and Date, so any help could be truly helpful. regards.
all the errors here:
javafx.fxml.LoadException:
/C:/Users/ROA%20PC/eclipse-workspace/Conexion/bin/application/Vista.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2579)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
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 application.Main.start(Main.java:23)
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)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.UnsupportedOperationException
at java.sql.Date.toInstant(Unknown Source)
at application.ConexionController.seleccionaregistros(ConexionController.java:190)
at application.ConexionController.initialize(ConexionController.java:92)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 17 more
Exception in Application start method
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 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(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
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(Unknown Source)
Caused by: java.lang.NullPointerException: Root cannot be null
at javafx.scene.Scene.<init>(Scene.java:336)
at javafx.scene.Scene.<init>(Scene.java:235)
at application.Main.start(Main.java:27)
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 application.Main
The java.sql.Date is a java.util.Date subclass that holds no time information, so you can’t convert it to an Instant class.
Fortunately, there is a toLocalDate method that does just that, convert it directly to LocalDate.
It should be like this:
rs.getDate(4).toLocalDate();
For further reference take a look at the JavaDoc https://docs.oracle.com/javase/8/docs/api/java/sql/Date.html#toInstant--

Exception thrown in main method in JavaFX

I'm facing some problems while executing my main function using javafx .It appears to be a problem in loading the fxml file if I'm not mistaken but I can't seem to find how to fix it .
Exception message:
Exception in Application start method 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 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(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)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$154(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalStateException: Location is not set.
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2434)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at Gestion.view.MainClass.initialisationContenu(MainClass.java:57)
at Gestion.view.MainClass.start(MainClass.java:28)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(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$147(WinApplication.java:177)
... 1 more
Exception running application Gestion.view.MainClass
Main function:
package Gestion.view;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MainClass extends Application {
private Stage stagePrincipal;
private BorderPane conteneurPrincipal;
#Override
public void start(Stage primaryStage) {
stagePrincipal = primaryStage;
stagePrincipal.setTitle("Application de gestion du centre socio-médical OCP");
initialisationConteneurPrincipal();
initialisationContenu();
}
private void initialisationConteneurPrincipal() {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainClass.class.getResource("Welcome.fxml"));
try {
conteneurPrincipal = (BorderPane) loader.load();
Scene scene = new Scene(conteneurPrincipal);
stagePrincipal.setScene(scene);
stagePrincipal.show();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initialisationContenu() {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass()
.getClassLoader()
.getResource("Acceuil1.fxml")
);
try {
AnchorPane conteneurPersonne = (AnchorPane) loader.load();
conteneurPrincipal.setCenter(conteneurPersonne);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
public Stage getStage() {
return null;
}
}
I've already searched in other similar questions , but the answers given did not work for me.
The problem is that FXMLLoader can't load an object hierarchy from FXML documents.
Fix it by updating the URLs:
loader.setLocation(MainClass.class.getResource("/fxml/Welcome.fxml"));
.getResource("/fxml/Acceuil1.fxml")
and moving Welcome.fxml and Acceuil1.fxml to src/main/resources/fxml directory.

NullPointerException while using two controller class together in javafx while opening csv file

I have two classes PersonOverviewController and RootLayoutController
I am trying to import a csv file from RootLayoutController and show it in the TableView which I have created in PersonOverViewController through the method onLoad() of RootLayoutController.. but is is giving me an exception...
package example.address.view;
import example.address.MainApp;
import example.address.model.Person;
import example.address.util.DateUtil;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
public class PersonOverviewController {
#FXML
public TableView<Person> personTable;
#FXML
public TableColumn<Person, String> firstNameColumn;
#FXML
public TableColumn<Person, String> lastNameColumn;
#FXML
public Label firstNameLabel;
#FXML
public Label lastNameLabel;
#FXML
private Label streetLabel;
#FXML
private Label postalCodeLabel;
#FXML
private Label cityLabel;
#FXML
private Label birthdayLabel;
#FXML
private Button btnLoad = new Button("Load");
// Reference to the main application.
private MainApp mainApp;
/**
* The constructor.
* The constructor is called before the initialize() method.
*/
public PersonOverviewController() {
}
/**
* Fills all text fields to show details about the person.
* If the specified person is null, all text fields are cleared.
*
* #param person the person or null
*/
private void showPersonDetails(Person person) {
if (person != null) {
// Fill the labels with info from the person object.
firstNameLabel.setText(person.getFirstName());
lastNameLabel.setText(person.getLastName());
streetLabel.setText(person.getStreet());
postalCodeLabel.setText(Integer.toString(person.getPostalCode()));
cityLabel.setText(person.getCity());
// TODO: We need a way to convert the birthday into a String!
birthdayLabel.setText(DateUtil.format(person.getBirthday()));
// birthdayLabel.setText(...);
} else {
// Person is null, remove all the text.
firstNameLabel.setText("");
lastNameLabel.setText("");
streetLabel.setText("");
postalCodeLabel.setText("");
cityLabel.setText("");
birthdayLabel.setText("");
}
}
/**
* Initializes the controller class. This method is automatically called
* after the fxml file has been loaded.
*/
#FXML
private void initialize() {
// Initialize the person table with the two columns.
firstNameColumn.setCellValueFactory(
cellData -> cellData.getValue().firstNameProperty());
lastNameColumn.setCellValueFactory(
cellData -> cellData.getValue().lastNameProperty());
// Clear person details.
showPersonDetails(null);
// Listen for selection changes and show the person details when changed.
personTable.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> showPersonDetails(newValue));
}
/**
* Is called by the main application to give a reference back to itself.
*
* #param mainApp
*/
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
// Add observable list data to the table
personTable.setItems(mainApp.getPersonData());
}
/**
* Called when the user clicks on the delete button.
*/
#FXML
private void handleDeletePerson() {
int selectedIndex = personTable.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0) {
personTable.getItems().remove(selectedIndex);
} else {
// Nothing selected.
Alert alert = new Alert(AlertType.WARNING);
alert.initOwner(mainApp.getPrimaryStage());
alert.setTitle("No Selection");
alert.setHeaderText("No Person Selected");
alert.setContentText("Please select a person in the table.");
alert.showAndWait();
}
}
/**
* Called when the user clicks the new button. Opens a dialog to edit
* details for a new person.
*/
#FXML
private void handleNewPerson() {
Person tempPerson = new Person();
boolean okClicked = mainApp.showPersonEditDialog(tempPerson);
if (okClicked) {
mainApp.getPersonData().add(tempPerson);
}
}
/**
* Called when the user clicks the edit button. Opens a dialog to edit
* details for the selected person.
*/
#FXML
private void handleEditPerson() {
Person selectedPerson = personTable.getSelectionModel().getSelectedItem();
if (selectedPerson != null) {
boolean okClicked = mainApp.showPersonEditDialog(selectedPerson);
if (okClicked) {
showPersonDetails(selectedPerson);
}
} else {
// Nothing selected.
Alert alert = new Alert(AlertType.WARNING);
alert.initOwner(mainApp.getPrimaryStage());
alert.setTitle("No Selection");
alert.setHeaderText("No Person Selected");
alert.setContentText("Please select a person in the table.");
alert.showAndWait();
}
}
}
and
package example.address.view;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Scanner;
import example.address.MainApp;
import example.address.model.Person;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.stage.FileChooser;
/**
* The controller for the root layout. The root layout provides the basic
* application layout containing a menu bar and space where other JavaFX
* elements can be placed.
*
* #author Marco Jakob
*/
public class RootLayoutController {
// Reference to the main application
private MainApp mainApp;
public ArrayList<Contacts> list;
private ListIterator<Contacts> LIT;
FileChooser fc = new FileChooser();
public ObservableList<Person> data;
PersonOverviewController overView = new PersonOverviewController();
/**
* Is called by the main application to give a reference back to itself.
*
* #param mainApp
*/
public void setMainApp(MainApp mainApp) {
this.mainApp = mainApp;
}
/**
* Creates an empty address book.
*/
#FXML
private void handleNew() {
mainApp.getPersonData().clear();
mainApp.setPersonFilePath(null);
}
/**
* Opens a FileChooser to let the user select an address book to load.
*/
#FXML
private void handleOpen() {
FileChooser fileChooser = new FileChooser();
// Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
"XML files (*.xml)", "*.xml");
fileChooser.getExtensionFilters().add(extFilter);
// Show save file dialog
File file = fileChooser.showOpenDialog(mainApp.getPrimaryStage());
if (file != null) {
mainApp.loadPersonDataFromFile(file);
}
}
/**
* Saves the file to the person file that is currently open. If there is no
* open file, the "save as" dialog is shown.
*/
#FXML
private void handleSave() {
File personFile = mainApp.getPersonFilePath();
if (personFile != null) {
mainApp.savePersonDataToFile(personFile);
} else {
handleSaveAs();
}
}
/**
* Opens a FileChooser to let the user select a file to save to.
*/
#FXML
private void handleSaveAs() {
FileChooser fileChooser = new FileChooser();
// Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
"XML files (*.xml)", "*.xml");
fileChooser.getExtensionFilters().add(extFilter);
// Show save file dialog
File file = fileChooser.showSaveDialog(mainApp.getPrimaryStage());
if (file != null) {
// Make sure it has the correct extension
if (!file.getPath().endsWith(".xml")) {
file = new File(file.getPath() + ".xml");
}
mainApp.savePersonDataToFile(file);
}
}
/**
* Opens an about dialog.
*/
#FXML
private void handleAbout() {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("AddressApp");
alert.setHeaderText("About");
alert.setContentText("STY");
alert.showAndWait();
}
/**
* Opens the birthday statistics.
*/
#FXML
private void handleShowBirthdayStatistics() {
mainApp.showBirthdayStatistics();
}
/**
* Closes the application.
*/
#FXML
private void handleExit() {
System.exit(0);
}
#FXML//Load CSV Data
public void onLoad()throws IOException {
data = FXCollections.observableArrayList();//Hold data for the table
File fileInfo = new File("C:/A_CSV/People.csv");
if(fileInfo.length()==0) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Information");
alert.setHeaderText("");
alert.setContentText("No Data in File at "+ fileInfo+"\n"+
"Enter Data and Save");
alert.showAndWait();
return;
}
fc.setTitle("Load Contacts Info");
fc.setInitialDirectory(new File("C:/"));
fc.setInitialDirectory(new File("C:/A_CSV"));
fc.setInitialFileName("People.csv");
File file = fc.showOpenDialog(null);
if (file == null) {
return;
}
String correctFile = file.getName();
if(!(correctFile.matches("People.csv"))){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Information");
alert.setHeaderText("");
alert.setContentText("The File at " + file + "\n\n"+
"is NOT accociated with this application\n\n"+
"Select the File at "+fileInfo);
alert.showAndWait();
return;
}
Path dirP = Paths.get(String.valueOf(file));
InputStream in = Files.newInputStream(dirP);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
list = new ArrayList<Contacts>();
Scanner scan = new Scanner(reader);
scan.useDelimiter(",");
// scan.useDelimiter("\\s*,\\s*");
while (scan.hasNext()){
String fname = scan.next();
String lname = scan.nextLine();
lname = lname.replaceAll(",", "");
overView.firstNameLabel.setText(String.valueOf(fname));
overView.lastNameLabel.setText(String.valueOf(lname));
list.add(new Contacts(fname,lname));
data.add(new Person(fname,lname));
overView.personTable.setItems(data);
overView.firstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
overView.lastNameColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
}
scan.close();
LIT = list.listIterator();
if (LIT.hasNext()){
Contacts p = LIT.next();
getContacts(p);
}
}
public void getContacts(Contacts p){
overView.firstNameLabel.setText("" + p.getFName());
overView.lastNameLabel.setText("" + p.getLName());
}
}
and it is giving me the error
Feb 15, 2016 1:28:39 PM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 8.0.65 by JavaFX runtime of version 8.0.45
Feb 15, 2016 1:28:43 PM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 8.0.65 by JavaFX runtime of version 8.0.45
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.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.control.MenuItem.fire(Unknown Source)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(Unknown Source)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$341(Unknown Source)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer$$Lambda$343/4980353.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.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$1500(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.lambda$handleMouseEvent$350(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$326/15265021.get(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
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.lambda$null$145(Unknown Source)
at com.sun.glass.ui.win.WinApplication$$Lambda$36/3326003.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)
... 47 more
Caused by: java.lang.NullPointerException
at example.address.view.RootLayoutController.onLoad(RootLayoutController.java:198)
... 56 more
what should i do?

Exception in Application start method java.lang.reflect.InvocationTargetException javafx

I write program with java8, JAVAFX, spring, hibernate, jpa, mysql.
I've to problem with connecting server part of program with javafx.
When I click on class with main→run as java aplication, this problems occurs:
log4j:WARN No appenders could be found for logger (org.jboss.resteasy.plugins.providers.DocumentProvider).
log4j:WARN Please initialize the log4j system properly.
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/Sylwia/.m2/repository/ch/qos/logback/logback-classic/1.0.13/logback-classic-1.0.13.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/Sylwia/.m2/repository/org/slf4j/slf4j-log4j12/1.7.5/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/Sylwia/.m2/repository/org/slf4j/slf4j-simple/1.5.8/slf4j-simple-1.5.8.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
Exception in Application start method
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 com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
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.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$147(Unknown Source)
at com.sun.javafx.application.LauncherImpl$$Lambda$48/1732398722.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: javafx.fxml.LoadException:
/C:/Users/Sylwia/git/Praca%20inzynierska%203/Praca%20inzynierska%202/target/classes/fxml/productComponent.fxml
at javafx.fxml.FXMLLoader.constructLoadException(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at pl.ftims.praca.restClientJavafx.RestClient.start(RestClient.java:17)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$153(Unknown Source)
at com.sun.javafx.application.LauncherImpl$$Lambda$51/1441419654.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(Unknown Source)
at com.sun.javafx.application.PlatformImpl$$Lambda$45/1051754451.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$164(Unknown Source)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/742445343.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(Unknown Source)
at com.sun.javafx.application.PlatformImpl$$Lambda$46/1775282465.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(Unknown Source)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/1109371569.run(Unknown Source)
... 1 more
Caused by: java.lang.NullPointerException
at pl.ftims.praca.restClientJavafx.FXMLController.initialize(FXMLController.java:140)
... 23 more
Exception running application pl.ftims.praca.restClientJavafx.RestClient
//////////////////////////////////////////////////////////////////////
Should I first focus on problem:
at pl.ftims.praca.restClientJavafx.RestClient.start(RestClient.java:17)
or:
Caused by: java.lang.NullPointerException
at pl.ftims.praca.restClientJavafx.FXMLController.initialize(FXMLController.java:140)
... 23 more
my RestClient class:
package pl.ftims.praca.restClientJavafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class RestClient extends Application {
#Override
public void start(Stage stage) throws Exception {
//When using the Class.getResource method,
//you must provide a local path from the location of the class on which is called the method.
//Parent root = FXMLLoader.load(RestClient.class.getResource("/fxml/components.fxml"));
Parent root = FXMLLoader.load(RestClient.class.getResource("/fxml/productComponent.fxml"));
//I also had to use Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));
/*FXMLLoader loader = new FXMLLoadergetClass().getResource("main.fxml");
loader.setController(new MainController(path));
Pane mainPane = loader.load();*/
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
FXMLController class
package pl.ftims.praca.restClientJavafx;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import pl.ftims.praca.model.ProductWrapper;
import pl.ftims.praca.model.Products;
public class FXMLController implements Initializable {
#FXML
private TableView productTable;
#FXML
private TableColumn idColumn;
#FXML
private TableColumn nameColumn;
#FXML
private TableColumn sellingPriceColumn;
#FXML
private TableColumn purchasePriceColumn;
#FXML
private TextField idField;//tego nie bylo chyba, bo nie mozna przeciez zmieniac id
#FXML
private TextField nameField;
#FXML
private TextField sellingPriceField;
#FXML
private TextField purchasePriceField;
/*private Long id;
private String name;
private Double sellingPrice;
private Double purchasePrice; //cena zakupu
#ManyToOne
private Storages storage; */
private List<Products> listOfProducts = null;
private List<Fxproduct> listOfFxProducts = null;
private ObservableList<Fxproduct> listOfObservableList = null;
private final static String REST_ROOT_URL = "http://localhost:8080/rest/";
private final Client client = ClientBuilder.newClient();
#FXML
private void remove(ActionEvent event) { //ok rozumiem
Fxproduct fxproduct = (Fxproduct) productTable.getSelectionModel().getSelectedItem();
listOfObservableList.remove(fxproduct);
Response response = client.target(REST_ROOT_URL).
// path("publisher").
path("products").
path("deleteProductWithId").
path(String.valueOf(fxproduct.getId())).
request().delete();
}
#FXML
private void save(ActionEvent event) {
Products product = new Products();
product.setName(nameField.getText());
product.setPurchasePrice(Double.parseDouble(purchasePriceField.getText()));
product.setSellingPrice(Double.parseDouble(sellingPriceField.getText()));
Entity<Products> kitapEntity = Entity.entity(product, MediaType.APPLICATION_XML);
Response response = client.target(REST_ROOT_URL).
path("product").
path("createProductWithData").
request().
post(kitapEntity);
list(null);
nameField.setText("");
purchasePriceField.setText("");
sellingPriceField.setText("");
}
#FXML
private void list(ActionEvent event) { //NIE WIEM JAK TO ZROBIC
Response response = client.target("http://localhost:8080/rest/").
path("products").
path("products").
request(MediaType.APPLICATION_XML).
get();
ProductWrapper productWrapper = response.readEntity(ProductWrapper.class); //nie mam tego
listOfProducts = (productWrapper.getProductList()==null)?new ArrayList<Products>(): productWrapper.getProductList();
// listOfFxProducts = new ArrayList<>();
// listOfFxProducts = new ArrayList<>(); //tak bylo, ale to jest java 1.7 i sie nie kompilowalo
for (Products k : listOfProducts) {
listOfFxProducts.add(new Fxproduct(k));
}
listOfObservableList = FXCollections.observableList(listOfFxProducts);
System.out.println(listOfObservableList);
productTable.setItems(listOfObservableList);
System.out.println(productTable);
}
public void kitapDuzenle(Products product) {
Entity<Products> kitapEntity = Entity.entity(product, MediaType.APPLICATION_XML);
Response response = client.target(REST_ROOT_URL).
path("product").
path("saveProduct2").
request().
put(kitapEntity);
}
// #SuppressWarnings("restriction")
#Override
public void initialize(URL url, ResourceBundle rb) {
productTable.setEditable(true); //tu jest blad, nullpointer
//NAME
nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
nameColumn.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Fxproduct, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Fxproduct, String> t) {
ObservableList<Fxproduct> kitapListesi = t.getTableView().getItems();
Fxproduct kitap = kitapListesi.get(t.getTablePosition().getRow());
kitap.setName(t.getNewValue());
kitapDuzenle(kitap.getproduct());
}
}
);
//SELLINGPRICE
sellingPriceColumn.setCellFactory(TextFieldTableCell.forTableColumn(new DoubleToStringConverter()));//tu jest blad
sellingPriceColumn.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Fxproduct, Double>>() {
#Override
public void handle(TableColumn.CellEditEvent<Fxproduct, Double> t) {
ObservableList<Fxproduct> kitapListesi = t.getTableView().getItems();
Fxproduct kitap = kitapListesi.get(t.getTablePosition().getRow());
kitap.setSellingPrice(t.getNewValue()); //tu ejst problem z double i siple double
kitapDuzenle(kitap.getproduct());
}
}
);
//PURCHASEPRICE
purchasePriceColumn.setCellFactory(TextFieldTableCell.forTableColumn(new DoubleToStringConverter()));
purchasePriceColumn.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Fxproduct, Double>>() {
#Override
public void handle(TableColumn.CellEditEvent<Fxproduct, Double> t) {
ObservableList<Fxproduct> kitapListesi = t.getTableView().getItems();
Fxproduct kitap = kitapListesi.get(t.getTablePosition().getRow());
kitap.setPurchasePrice(t.getNewValue());//tu ejst problem z double i siple double
kitapDuzenle(kitap.getproduct());
}
}
);
idColumn.setCellValueFactory(
new PropertyValueFactory<Fxproduct, Long>("id"));
nameColumn.setCellValueFactory(
new PropertyValueFactory<Fxproduct, String>("name"));
purchasePriceColumn.setCellValueFactory(
new PropertyValueFactory<Fxproduct, Double>("price"));
sellingPriceColumn.setCellValueFactory(
new PropertyValueFactory<Fxproduct, Double>("price"));
list(null);
}
}
I thought that the problems is the path:
Parent root = FXMLLoader.load(RestClient.class.getResource("/fxml/productComponent.fxml"));
but I read this:
How to reference javafx fxml files in resource folder?
JavaFX "Location is required." even though it is in the same package
Referencing class resource in FXML
Error loading fxml files from a folder other than the bin folder
JavaFX: load resource from other package - NetBeans
How to reference javafx fxml files in resource folder?
https://stackexchange.com/search?q=How+to+reference+javafx+fxml+files+in+resource+folder%3F
JavaFX - Exception in Application start method?
and I didnt find the answer.
/////////////////////////////EDIT///////////////////
line 17 in RestClient:
Parent root = FXMLLoader.load(RestClient.class.getResource("/fxml/productComponent.fxml"));
line 139, 140 in FXMLController:
public void initialize(URL url, ResourceBundle rb) { productTable.setEditable(true); // nullpointer

java.lang.NullPointerException for Multi Screens JavaFX/FXML

So, I'm doing a JavaFX multiview GUI application.
Below is the code so that you can refer to it, don't read through it to find an error yet, I'll explain the problem underneath first ;)
I have a main - which starts the application
public class MyFXMLMain extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Wireframe.fxml"));
stage.setTitle("My Fitness App");
Scene mainScene = new Scene(root,805,809);
stage.setScene(mainScene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
ScreensController - that controls loading/setting screens.
public class ScreensController extends StackPane {
private HashMap<String, Node> screens = new HashMap<>();
public ScreensController() {
super();
}
public void addScreen(String name, Node screen) {
screens.put(name, screen);
}
public Node getScreen(String name) {
return screens.get(name);
}
public boolean loadScreen(String name, String resource) {
try {
FXMLLoader myLoader = new FXMLLoader(getClass().getResource(resource));
Parent loadScreen = (Parent) myLoader.load();
ControlledScreen myScreenController = ((ControlledScreen) myLoader.getController());
myScreenController.setScreenParent(this);
addScreen(name, loadScreen);
return true;
}catch(Exception e) {
System.out.println(e.getMessage());
return false;
}
}
public boolean setScreen(final String name) {
if (screens.get(name) != null) { //screen loaded
final DoubleProperty opacity = opacityProperty();
if (!getChildren().isEmpty()) { //if there is more than one screen
Timeline fade = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 1.0)),
new KeyFrame(new Duration(1000), new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
getChildren().remove(0); //remove the displayed screen
getChildren().add(0, screens.get(name)); //add the screen
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(800), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
}, new KeyValue(opacity, 0.0)));
fade.play();
} else {
setOpacity(0.0);
getChildren().add(screens.get(name)); //no one else been displayed, then just show
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(2500), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
return true;
} else {
System.out.println("screen hasn't been loaded!!! \n");
return false;
}
}
public boolean unloadScreen(String name) {
if (screens.remove(name) == null) {
System.out.println("Screen didn't exist");
return false;
} else {
return true;
}
}
}
A screen framework - that links the screens to the FXML files.
public class ScreensFramework extends Application {
public static String MAIN_SCREEN = "MyFXMLController";
public static String MAIN_SCREEN_FXML = "Wireframe.fxml";
public static String calendarScreen = "CalendarscreenController";
public static String calendarScreenFXML = "Calendarscreen.fxml";
public static String guideScreen = "GuideScreenController";
public static String guideScreenFXML ="Guidescreen.fxml";
#Override
public void start(Stage primaryStage) {
ScreensController mainContainer = new ScreensController();
mainContainer.loadScreen(ScreensFramework.MAIN_SCREEN, ScreensFramework.MAIN_SCREEN_FXML);
mainContainer.loadScreen(ScreensFramework.calendarScreen,ScreensFramework.calendarScreenFXML);
mainContainer.loadScreen(ScreensFramework.guideScreen,ScreensFramework.guideScreenFXML);
mainContainer.setScreen(ScreensFramework.MAIN_SCREEN);
Group root = new Group();
root.getChildren().addAll(mainContainer);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
}
An FXML controller - which links to the FXML files and tells FXML what to do when something is clicked.
public class MyFXMLController implements ControlledScreen{
#FXML private TextField givenName;
#FXML private Text targetText;
//#FXML private static TableView<Mass> theTable;
//#FXML private static TableColumn<Mass, String> dateCol;
//#FXML private static TableColumn<Mass, String> massCol;
#FXML private static LineChart<Number,Number> weightChart;
#FXML private static NumberAxis axisX;
#FXML private static NumberAxis axisY;
#FXML private static Label myLabel;
//private static User theUser = new User();
private static ScreensController myController;
#Override
public void setScreenParent(ScreensController screenPage) {
myController = screenPage;
}
#FXML protected void handlePressedCalendarButtonAction(ActionEvent event){
System.out.println("Hello");
}
#FXML protected void mouseclickedcal(MouseEvent mec){
myController.setScreen(ScreensFramework.calendarScreen);
}
}
A controlledscreen - that does this:
public interface ControlledScreen {
public void setScreenParent(ScreensController screenPage);
}
And a CalendarScreenController - that controls one of the multi screens
public class CalendarScreenController implements Initializable, ControlledScreen {
ScreensController myController;
#Override
public void initialize(URL url, ResourceBundle rb) {
}
public void setScreenParent(ScreensController screenParent){
myController = screenParent;
}
#FXML
private void goToMain(ActionEvent event){
myController.setScreen(ScreensFramework.MAIN_SCREEN);
}
}
PROBLEM BELOW
When I run my program it works fine, but then if I click on a button that activates the calendar onclick code here:
#FXML protected void mouseclickedcal(MouseEvent mec){
myController.setScreen(ScreensFramework.calendarScreen);
}
which should set the screen to CalendarScreen.fxml,one of my multi screens but instead, it causes an error below:
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
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.Scene$ClickGenerator.postProcess(Unknown Source)
at javafx.scene.Scene$ClickGenerator.access$8600(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1900(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$100(Unknown Source)
at com.sun.glass.ui.win.WinApplication$3$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)
... 31 more
Caused by: java.lang.NullPointerException
at myfxml.MyFXMLController.mouseclickedcal(MyFXMLController.java:125)
... 40 more
Line 125 is the code:
#FXML protected void mouseclickedcal(MouseEvent mec){
myController.setScreen(ScreensFramework.calendarScreen);
}
Thank you so much for having a look at this. I can't seem to find the error ;(
Turns out I had 2 mains and they were conflicting and also in my xml code I was calling something that didn't exist in its controller.

Resources