I'm new to JavaFX and I'm just trying to populate a tableview defined in FXML from a CSV text file. My code is as follows:
package student;
import java.net.URL;
import java.util.*;
import javafx.fxml.*;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
public class StudInfoController implements Initializable {
#FXML
private Tab profile;
#FXML
private Label namelbl;
#FXML
private Label clslbl;
#FXML
private Label divlbl;
#FXML
private Label rnolbl;
#FXML
private Label maillbl;
#FXML
private Label moblbl;
#FXML
private Label altlbl;
#FXML
private Tab exams;
#FXML
private Tab result;
#FXML
private TableView<Exam> ExamTable;
#FXML
private TableView<Result> ResultTable;
#FXML
private TableColumn<Exam, String> eSub;
#FXML
private TableColumn<Exam, String> eDate;
#FXML
private TableColumn<Exam, String> eDur;
#FXML
private TableColumn<Exam, String> eMarks;
#FXML
private TableColumn<Result, String> rSub;
#FXML
private TableColumn<Result, String> rDate;
#FXML
private TableColumn<Result, String> rTT;
#FXML
private TableColumn<Result, String> rTE;
#FXML
private TableColumn<Result, String> rMarks;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
eSub.setCellValueFactory(new PropertyValueFactory<>("eSub"));
eDate.setCellValueFactory(new PropertyValueFactory<>("eDate"));
eDur.setCellValueFactory(new PropertyValueFactory<>("eDur"));
eMarks.setCellValueFactory(new PropertyValueFactory<>("eMarks"));
rSub.setCellValueFactory(new PropertyValueFactory<>("rSub"));
rDate.setCellValueFactory(new PropertyValueFactory<>("rDate"));
rTT.setCellValueFactory(new PropertyValueFactory<>("rTT"));
rTE.setCellValueFactory(new PropertyValueFactory<>("rTE"));
rMarks.setCellValueFactory(new PropertyValueFactory<>("rMarks"));
ExamTable.getItems().setAll(InsertExam());
ResultTable.getItems().setAll(InsertResult());
}
private List<Exam> InsertExam() {
try {
FileRead fr = new FileRead();
String[] l = fr.examRead();
String[] items;
int i = 0;
Exam r = new Exam();
List<Exam> row = new ArrayList<>();
for (i = 0; i < l.length; i++) {
items = l[i].split(",");
r.setESub(items[0]);
r.setEDate(items[1]);
r.setEDur(items[2]);
r.setEMarks(items[3]);
row.add(r);
}
return row;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private List<Result> InsertResult() {
try {
FileRead fr = new FileRead();
String[] l = fr.resultRead();
String[] items;
Result r = new Result();
List<Result> row = new ArrayList<>();
for (int i = 0; i < l.length; i++) {
items = l[i].split(",");
r.setRSub(items[0]);
r.setRDate(items[1]);
r.setRTT(items[2]);
r.setRTE(items[3]);
r.setRMarks(items[4]);
row.add(r);
}
return row;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
class Exam {
private String eSub;
private String eDate;
private String eDur;
private String eMarks;
public Exam() {
}
public String getESub() {
return eSub;
}
public void setESub(String eSub) {
this.eSub = eSub;
}
public String getEDate() {
return eDate;
}
public void setEDate(String eDate) {
this.eDate = eDate;
}
public String getEDur() {
return eDur;
}
public void setEDur(String eDur) {
this.eDur = eDur;
}
public String getEMarks() {
return eMarks;
}
public void setEMarks(String eMarks) {
this.eMarks = eMarks;
}
}
class Result {
private String rSub;
private String rDate;
private String rTT;
private String rTE;
private String rMarks;
public String getRSub() {
return rSub;
}
public void setRSub(String rSub) {
this.rSub = rSub;
}
public String getRDate() {
return rDate;
}
public void setRDate(String rDate) {
this.rDate = rDate;
}
public String getRTT() {
return rTT;
}
public void setRTT(String rTT) {
this.rTT = rTT;
}
public String getRTE() {
return rTE;
}
public void setRTE(String rTE) {
this.rTE = rTE;
}
public String getRMarks() {
return rMarks;
}
public void setRMarks(String rMarks) {
this.rMarks = rMarks;
}
public Result() {
}
}
}
The FXML code is as follows:
<TableView fx:id="ResultTable" prefHeight="345.0" prefWidth="697.0">
<columns>
<TableColumn fx:id="rSub" editable="false" prefWidth="297.0"
text="SUBJECT"/>
<TableColumn fx:id="rDate" editable="false" prefWidth="97.0"
text="DATE" />
<TableColumn fx:id="rTT" editable="false" prefWidth="123.0"
text="TOTAL TIME"/>
<TableColumn fx:id="rTE" editable="false" prefWidth="116.0"
text="TIME ELAPSED" />
<TableColumn fx:id="rMarks" editable="false" prefWidth="63.0"
text="MARKS" />
</columns>
</TableView>
<TableView fx:id="ExamTable" prefHeight="344.0" prefWidth="697.0">
<columns>
<TableColumn fx:id="eSub" editable="false" prefWidth="414.0"
text="SUBJECT" />
<TableColumn fx:id="eDate" editable="false" prefWidth="148.0"
text="DATE" />
<TableColumn fx:id="eDur" editable="false" prefWidth="79.0"
text="DURATION" />
<TableColumn fx:id="eMarks" editable="false" prefWidth="55.0"
text="MARKS" />
</columns>
</TableView>
The following exception is being thrown:
Executing C:\Users\ANIL\Documents\NetBeansProjects\Student\dist\run775021387\Student.jar using platform C:\Program Files\Java\jdk1.8.0_111\jre/bin/java
java.lang.RuntimeException: java.lang.IllegalAccessException: Class sun.reflect.misc.Trampoline can not access a member of class student.StudInfoController$Result with modifiers "public"
at com.sun.javafx.property.PropertyReference.get(PropertyReference.java:177)
at javafx.scene.control.cell.PropertyValueFactory.getCellDataReflectively(PropertyValueFactory.java:147)
at javafx.scene.control.cell.PropertyValueFactory.call(PropertyValueFactory.java:119)
at javafx.scene.control.cell.PropertyValueFactory.call(PropertyValueFactory.java:98)
at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:578)
at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:563)
at javafx.scene.control.TableCell.updateItem(TableCell.java:644)
at javafx.scene.control.TableCell.indexChanged(TableCell.java:468)
at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:116)
at com.sun.javafx.scene.control.skin.TableRowSkinBase.updateCells(TableRowSkinBase.java:533)
at com.sun.javafx.scene.control.skin.TableRowSkinBase.init(TableRowSkinBase.java:147)
at com.sun.javafx.scene.control.skin.TableRowSkin.<init>(TableRowSkin.java:64)
at javafx.scene.control.TableRow.createDefaultSkin(TableRow.java:212)
at javafx.scene.control.Control.impl_processCSS(Control.java:872)
at javafx.scene.Node.processCSS(Node.java:9058)
at javafx.scene.Node.applyCss(Node.java:9155)
at com.sun.javafx.scene.control.skin.VirtualFlow.setCellIndex(VirtualFlow.java:1964)
at com.sun.javafx.scene.control.skin.VirtualFlow.getCell(VirtualFlow.java:1797)
at com.sun.javafx.scene.control.skin.VirtualFlow.getCellLength(VirtualFlow.java:1879)
at com.sun.javafx.scene.control.skin.VirtualFlow.computeViewportOffset(VirtualFlow.java:2528)
at com.sun.javafx.scene.control.skin.VirtualFlow.layoutChildren(VirtualFlow.java:1189)
at javafx.scene.Parent.layout(Parent.java:1087)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Scene.doLayoutPass(Scene.java:552)
at javafx.scene.Scene.preferredSize(Scene.java:1646)
at javafx.scene.Scene.impl_preferredSize(Scene.java:1720)
at javafx.stage.Window$9.invalidated(Window.java:846)
at javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:109)
at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:144)
at javafx.stage.Window.setShowing(Window.java:922)
at javafx.stage.Window.show(Window.java:937)
at javafx.stage.Stage.show(Stage.java:259)
at student.StudentFXMLController.OKBtnAction(StudentFXMLController.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8413)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:380)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:294)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:416)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalAccessException: Class sun.reflect.misc.Trampoline can not access a member of class student.StudInfoController$Result with modifiers "public"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
at java.lang.reflect.Method.invoke(Method.java:491)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at com.sun.javafx.property.PropertyReference.get(PropertyReference.java:175)
... 94 more
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.IllegalAccessException: Class sun.reflect.misc.Trampoline can not access a member of class student.StudInfoController$Result with modifiers "public"
at com.sun.javafx.property.PropertyReference.get(PropertyReference.java:177)
at javafx.scene.control.cell.PropertyValueFactory.getCellDataReflectively(PropertyValueFactory.java:147)
at javafx.scene.control.cell.PropertyValueFactory.call(PropertyValueFactory.java:119)
at javafx.scene.control.cell.PropertyValueFactory.call(PropertyValueFactory.java:98)
at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:578)
at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:563)
at javafx.scene.control.TableCell.updateItem(TableCell.java:644)
at javafx.scene.control.TableCell.indexChanged(TableCell.java:468)
at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:116)
at com.sun.javafx.scene.control.skin.TableRowSkinBase.updateCells(TableRowSkinBase.java:533)
at com.sun.javafx.scene.control.skin.TableRowSkinBase.init(TableRowSkinBase.java:147)
at com.sun.javafx.scene.control.skin.TableRowSkin.<init>(TableRowSkin.java:64)
at javafx.scene.control.TableRow.createDefaultSkin(TableRow.java:212)
at javafx.scene.control.Control.impl_processCSS(Control.java:872)
at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
at javafx.scene.control.Control.impl_processCSS(Control.java:868)
at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
at javafx.scene.Parent.impl_processCSS(Parent.java:1280)
at javafx.scene.control.Control.impl_processCSS(Control.java:868)
at javafx.scene.Node.processCSS(Node.java:9058)
at javafx.scene.Node.processCSS(Node.java:9051)
at javafx.scene.Scene.doCSSPass(Scene.java:545)
at javafx.scene.Scene.access$3600(Scene.java:159)
at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2392)
at com.sun.javafx.tk.Toolkit.lambda$runPulse$30(Toolkit.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:354)
at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:381)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:510)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:490)
at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$404(QuantumToolkit.java:319)
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(Thread.java:745)
Caused by: java.lang.IllegalAccessException: Class sun.reflect.misc.Trampoline can not access a member of class student.StudInfoController$Result with modifiers "public"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
at java.lang.reflect.Method.invoke(Method.java:491)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at com.sun.javafx.property.PropertyReference.get(PropertyReference.java:175)
... 37 more
Well the issue was with the class declaration. the class has to be public. And the issue is resolved. thanks for the help
Related
I'm just starting out with JavaFX, and I am trying to build a ARP Spoofing Tool for School's Project. But when I run code, I'm getting this problem.
I tried reading many answers found on Stack Overflow. I even tried making the project again from the beginning. But I keep on getting the same error.
Here is code.
controller.java
package controller;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapIf;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class Main extends Application {
public static Pcap pcap = null;
public static PcapIf device = null;
private Stage primaryStage;
private AnchorPane layout;
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("JavaFX ARP Spoofing Tool");
setLayout();
}
public void setLayout() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("../view/View.fxml"));
layout = (AnchorPane) loader.load();
Scene scene = new Scene(layout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
}
View.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.collections.*?>
<AnchorPane prefHeight="480.0" prefWidth="490.0"
fx:controller="controller.Controller"
xmlns="http://javafx.com/javafx/8.0.111"
xmlns:fx="http://javafx.com/fxml/1">
<children>
<ListView fx:id="networkListView" layoutX="15.0" layoutY="14.0"
prefHeight="78.0" prefWidth="462.0">
<items>
<FXCollection fx:factory="observableArrayList" />
</items>
</ListView>
<Button fx:id="pickButton" onAction="#networkPickAction"
layoutX="395.0" layoutY="103.0"
prefHeight="29.0" prefWidth="82.0" text="PICK" />
<TextArea fx:id="textArea" editable="false" layoutX="15.0"
layoutY="144.0"
prefHeight="325.0" prefWidth="462.0" />
</children>
</AnchorPane>
Main.java
package controller;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapIf;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
public class Controller implements Initializable {
#FXML
private ListView<String> networkListView;
#FXML
private TextArea textArea;
#FXML
private Button pickButton;
ObservableList<String> networkList = FXCollections.observableArrayList();
private ArrayList<PcapIf> allDevs = null;
#Override
public void initialize(URL location, ResourceBundle resources) {
allDevs = new ArrayList<PcapIf>();
StringBuilder errbuf = new StringBuilder();
int r = Pcap.findAllDevs(allDevs, errbuf);
if (r == Pcap.NOT_OK || allDevs.isEmpty()) {
textArea.appendText("Failed to find network device.\n" + errbuf.toString() + "\n");
return;
}
textArea.appendText("A network device detected.\nChoose the device.\n");
for (PcapIf device : allDevs) {
networkList.add(device.getName() + " " +
((device.getDescription() != null) ? device.getDescription(): "No Description"));
}
networkListView.setItems(networkList);
}
public void networkPickAction() {
if(networkListView.getSelectionModel().getSelectedIndex() < 0) {
return;
}
Main.device = allDevs.get(networkListView.getSelectionModel().getSelectedIndex());
networkListView.setDisable(true);
pickButton.setDisable(true);
int snaplen = 64 * 1024;
int flags = Pcap.MODE_PROMISCUOUS;
int timeout = 1;
StringBuilder errbuf = new StringBuilder();
Main.pcap = Pcap.openLive(Main.device.getName(), snaplen, flags, timeout, errbuf);
if(Main.pcap == null) {
textArea.appendText("Failed to open the network device.\n" + errbuf.toString() + "\n");
return;
}
textArea.appendText("Choose the device: " + Main.device.getName() + "\n");
textArea.appendText("Activated the device.\n");
}
}
When I click on class with main→run as java application, this problems occurs:
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$159(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.UnsatisfiedLinkError: com.slytechs.library.NativeLibrary.dlopen(Ljava/lang/String;)J
at com.slytechs.library.NativeLibrary.dlopen(Native Method)
at com.slytechs.library.NativeLibrary.<init>(Unknown Source)
at com.slytechs.library.JNILibrary.<init>(Unknown Source)
at com.slytechs.library.JNILibrary.loadLibrary(Unknown Source)
at com.slytechs.library.JNILibrary.register(Unknown Source)
at com.slytechs.library.JNILibrary.register(Unknown Source)
at com.slytechs.library.JNILibrary.register(Unknown Source)
at org.jnetpcap.Pcap.<clinit>(Unknown Source)
at controller.Controller.initialize(Controller.java:37)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
at controller.Main.setLayout(Main.java:31)
at controller.Main.start(Main.java:24)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$166(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$179(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$177(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$178(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$152(WinApplication.java:177)
... 1 more
Exception running application controller.Main
This question already has an answer here:
Why my JavaFX TableView is empty
(1 answer)
Closed 4 years ago.
hello everyone the Date value does not showing in the tableview, i pass the correct parameters but i think i need to format the Date data to transform that data to a string value, i am using the Object Property for the Date and the SimpleStringProperty and SimpleIntergerProperty for the name, lastname, and ID
in the Insert Method i used preparedstatement to save the data in the Database, that seems ok, i declare in the database fecha_nacimiento as Date, but when i am showing the date data into the tableview, like i said before the tablecolumn appears empy
i put all my code here to revision or improvement of that error, i need some help to review the process in setting or formating the value of the table column date to string.
any help could be helpful. regards.
date data empy in tableview:
modifications 1 in the controller #Daniel Subelman:
modifications 2 class persona #Daniel Subelman:
issue after modifications #Daniel Subelman:
constructor exception error 1:
unsopported operation error:
nulpointer exception error:
here is my controller code
package application;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.MenuBar;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class ConexionController implements Initializable {
#FXML TableView<Persona> tablacliente;
#FXML TableColumn<Persona, String> nombrescol;
#FXML TableColumn<Persona,String > apellidoscol;
#FXML TableColumn<Persona, Integer> clienteid;
#FXML TableColumn<Persona,LocalDate> fechacli;
ResultSet rs=null;
Connection Conexion=null;
#FXML private Button btn;
#FXML private Button mtn;
#FXML private Button lmp;
#FXML private Button mts;
#FXML private Button bqd;
#FXML private Button bqape;
#FXML private TextField nm;
#FXML private TextField ap;
#FXML private TextField bq;
#FXML private TextField bqa;
#FXML private MenuBar menucombo;
#FXML private Button botonborrar;
#FXML private TextField borrar;
#FXML private DatePicker mifecha;
#Override
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 borraregistro() {
int id = Integer.parseInt(borrar.getText());
String consulta=" delete from cliente where id=? ";
Connection conn=null;{
try {
conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
PreparedStatement ps =conn.prepareStatement(consulta);
ps.setInt(1, id);
ps.executeQuery();
}catch (SQLException e) {
e.printStackTrace();
}
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Informacion");
alert.setHeaderText(null);
alert.setContentText("Registro borrado correctamente");
alert.showAndWait();
}
seleccionaregistros();
}
public void conexion(){
try {
Conexion=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
}
catch (SQLException e) {
e.printStackTrace();
}
if(Conexion!=null) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Informacion");
alert.setHeaderText(null);
alert.setContentText("Conexion Exitosa");
alert.showAndWait();
}
}
public void insertaregistro() {
Connection conn=null;
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
Statement insertar=conn.createStatement();
insertar.executeUpdate("insert into cliente (nombre, apellido,fecha_nacimiento) values ('"+nm.getText()+"', '"+ap.getText()+"', '"+((TextField)mifecha.getEditor()).getText()+"')");
if(conn!=null) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Informacion");
alert.setHeaderText(null);
alert.setContentText("Registro Insertado correctamente");
alert.showAndWait();
}
} catch (SQLException e) {
e.printStackTrace();
}
seleccionaregistros();
}
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();
}
}
}
public void seleccionanombre() {
String nombre = bq.getText();
ObservableList <Persona> busqueda =FXCollections.observableArrayList();
String consulta=" select * from cliente where nombre like ? " ;
Connection conn=null;{
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
PreparedStatement ps =conn.prepareStatement(consulta);
ps.setString(1, nombre);
ResultSet rs =ps.executeQuery();
while ( rs.next() )
{
busqueda.add(new Persona(
rs.getString("nombre"),
rs.getString("apellido"),
rs.getInt("id"),
rs.getDate(4).toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
);
}
} catch (SQLException e) {
e.printStackTrace();
}
tablacliente.setItems(busqueda);
}
}
public void seleccionapellido() {
String apellido = bqa.getText();
ObservableList <Persona> busquedape =FXCollections.observableArrayList();
String consulta=" select * from cliente where apellido like ? " ;
Connection conn=null;{
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=prueba", "sa", "milkas87");
PreparedStatement ps =conn.prepareStatement(consulta);
ps.setString(1, apellido);
ResultSet rs =ps.executeQuery();
while ( rs.next() )
{
busquedape.add(new Persona(
rs.getString("nombre"),
rs.getString("apellido"),
rs.getInt("id"),
rs.getDate(4).toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
);
}
} catch (SQLException e) {
e.printStackTrace();
}
tablacliente.setItems(busquedape);
}
}
public void inicializacombo() {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("VistaCombo.fxml"));
Scene scene = new Scene(fxmlLoader.load());
Stage stage = new Stage();
stage.setTitle("Datos Del Cliente");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
}
}
public void limpiatexto() {
nm.clear();
ap.clear();
bq.clear();
bqa.clear();
borrar.clear();
}
public void cargarconexion() {
btn.setOnAction(e->{
conexion();
});
}
public void cargarregistro() {
mtn.setOnAction(e->{
insertaregistro();
});
}
public void borrarcasillatexto() {
lmp.setOnAction(e->{
limpiatexto();
});
}
public void mostrartodo() {
mts.setOnAction(e->{
seleccionaregistros();
});
}
public void buscanm() {
bqd.setOnAction(e->{
seleccionanombre();
});
}
public void buscaape() {
bqape.setOnAction(e->{
seleccionapellido();
});
}
public void borraregistroid() {
botonborrar.setOnAction(e->{
borraregistro();
});
}
}
here 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);
}
}
here is my FXML code
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="497.0" prefWidth="943.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.ConexionController">
<children>
<Pane layoutY="-3.0" prefHeight="605.0" prefWidth="1084.0">
<children>
<Button fx:id="btn" layoutX="145.0" layoutY="109.0" mnemonicParsing="false" onAction="#cargarconexion" prefHeight="46.0" prefWidth="117.0" text="Prueba Conexion" />
<Button fx:id="mtn" layoutX="15.0" layoutY="183.0" mnemonicParsing="false" onAction="#cargarregistro" prefHeight="46.0" prefWidth="117.0" text="Inserta Registro" />
<Label layoutX="14.0" layoutY="279.0" prefHeight="17.0" prefWidth="105.0" text="NOMBRES" />
<Label layoutX="15.0" layoutY="327.0" prefHeight="17.0" prefWidth="79.0" text="APELLIDOS" />
<TextField fx:id="nm" layoutX="159.0" layoutY="275.0" prefHeight="25.0" prefWidth="149.0" />
<TextField fx:id="ap" layoutX="159.0" layoutY="323.0" />
<Button fx:id="lmp" layoutX="159.0" layoutY="484.0" mnemonicParsing="false" onAction="#borrarcasillatexto" prefHeight="25.0" prefWidth="150.0" text="Limpiar Texto" />
<TableView fx:id="tablacliente" layoutX="355.0" layoutY="15.0" prefHeight="383.0" prefWidth="696.0">
<columns>
<TableColumn fx:id="clienteid" prefWidth="159.0" text="ID" />
<TableColumn fx:id="nombrescol" prefWidth="159.0" text="NOMBRES" />
<TableColumn fx:id="apellidoscol" minWidth="0.0" prefWidth="169.0" text="APELLIDOS" />
<TableColumn fx:id="fechacli" prefWidth="235.0" text="FECHA DE NACIMIENTO" />
</columns>
</TableView>
<Button fx:id="mts" layoutX="15.0" layoutY="109.0" mnemonicParsing="false" onAction="#mostrartodo" prefHeight="46.0" prefWidth="117.0" text="Mostrar" />
<TextField fx:id="bq" layoutX="554.0" layoutY="417.0" prefHeight="25.0" prefWidth="149.0" />
<Button fx:id="bqd" layoutX="758.0" layoutY="417.0" mnemonicParsing="false" onAction="#buscanm" prefHeight="25.0" prefWidth="155.0" text="BUSCAR NOMBRE" />
<Button fx:id="bqape" layoutX="758.0" layoutY="458.0" mnemonicParsing="false" onAction="#buscaape" prefHeight="25.0" prefWidth="155.0" text="BUSCAR POR APELLIDO" />
<TextField fx:id="bqa" layoutX="554.0" layoutY="458.0" />
<ComboBox layoutX="159.0" layoutY="430.0" prefWidth="150.0" />
<Label layoutX="15.0" layoutY="434.0" prefHeight="17.0" prefWidth="55.0" text="GENERO" />
<MenuBar fx:id="menucombo" layoutY="3.0">
<menus>
<Menu mnemonicParsing="false" text="Agregar">
<items>
<MenuItem mnemonicParsing="false" onAction="#inicializacombo" text="Datos Cliente" />
</items>
</Menu>
</menus>
</MenuBar>
<Button fx:id="botonborrar" layoutX="758.0" layoutY="507.0" mnemonicParsing="false" onAction="#borraregistroid" prefHeight="25.0" prefWidth="155.0" text="BORRAR REGISTRO" />
<TextField fx:id="borrar" layoutX="554.0" layoutY="507.0" />
<DatePicker fx:id="mifecha" layoutX="158.0" layoutY="371.0" prefHeight="25.0" prefWidth="150.0" />
<Label layoutX="15.0" layoutY="375.0" prefHeight="17.0" prefWidth="150.0" text="FECHA DE NACIMIENTO" />
</children>
</Pane>
</children>
</AnchorPane>
this is the error in the console
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
I had to adapt your code to make it work without connecting to the DB. This changes will make it work.
In your Persona class:
Change your constructor to:
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);
}
Change the getter and setter for fechacliente:
public LocalDate getFechaCliente() {
return fechacliente.get();
}
public void setFechaCliente(LocalDate fechacliente) {
this.fechacliente = new SimpleObjectProperty<>(fechacliente);
}
Add fechaClienteProperty:
public ObjectProperty<LocalDate> fechaClienteProperty() {
return fechacliente;
}
In your ConexionController change the CellValueFactory and CellFactory to:
fechacli.setCellValueFactory(cellData -> cellData.getValue().fechaClienteProperty());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMyyyy");
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));
}
}
};
});
With this corrections it works. Hope this helps.
I am having a problem opening a FileChooser in JavaFX as it throws an error when i call showOpenDialog(...) method, i searched for similar threads like the link i posted below but couldn't make it work.
The error is thrown when i call the addHtml() method on EmailSenderController to add the html file text to the html editor.
Similar thread but with the exception that i didn't initialize the #FXML injected controls like he did : JavaFX FileChooser Throws Error (probably easy fix, but still confused)
Main class
package emailsender;
import configuration.ProjectConfiguration;
import emailsender.controllers.EmailSenderController;
import emailsender.services.FileReaderService;
import emailsender.services.ViewLoaderService;
import java.io.IOException;
import javafx.application.Application;
import javafx.stage.Stage;
/**
*
* #author DJava
*/
public class EmailSender extends Application {
#Override
public void start(Stage primaryStage) throws IOException, Exception
{
//Main configuration
ProjectConfiguration configuration = new
ProjectConfiguration();
configuration.setStage(primaryStage);
configuration.setViewsPath("emailsender/views/");
//Services
ViewLoaderService viewloaderService = new
ViewLoaderService(configuration);
FileReaderService fileReaderService = new
FileReaderService(configuration);
//Controllers
EmailSenderController sender = new
EmailSenderController(viewloaderService, fileReaderService);
sender.start(configuration.getStage());
}
public static void main(String[] args) {
launch(args);
}
}
View Loader Service
package emailsender.services;
import configuration.ProjectConfiguration;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
/**
*
* #DJava
*/
public class ViewLoaderService {
ProjectConfiguration configuration;
public ViewLoaderService(ProjectConfiguration configuration) {
this.configuration = configuration;
}
public Scene loadViewOnScene(String view) throws IOException {
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource(this.configuration.getViewsPath() + view + ".fxml"));
return new Scene(root);
}
}
Controller
package emailsender.controllers;
import emailsender.services.FileReaderService;
import javafx.application.Application;
import javafx.stage.Stage;
import emailsender.services.ViewLoaderService;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextField;
import javafx.scene.web.HTMLEditor;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
/**
*
* #author DJava
*/
public class EmailSenderController extends Application {
private ViewLoaderService viewLoaderService;
private FileReaderService fileReaderService;
private WebEngine webEngine;
//Header
//EmaiLSender menu
#FXML
public MenuItem newListMenuItem;
#FXML
public MenuItem preferencesMenuItem;
#FXML
public MenuItem closeMenuItem;
//Help menu
#FXML
public MenuItem aboutMenuItem;
//Email tab
#FXML
public TextField subjectTextField;
#FXML
public ComboBox destinationListComboBox;
#FXML
public Button addHtmlButton;
#FXML
public HTMLEditor messageEditor;
#FXML
public ProgressIndicator sendTaskProgressIndicator;
//Preview tab
#FXML
public WebView previewWebView;
//Footer
#FXML
public Button sendButton;
public EmailSenderController() {
}
public EmailSenderController(ViewLoaderService viewLoaderService,
FileReaderService fileReaderService) {
this.viewLoaderService = viewLoaderService;
this.fileReaderService = fileReaderService;
}
#FXML
public void addHtml() {
this.messageEditor.setHtmlText
(this.fileReaderService.getFileText()); // Here is the problem ..........
}
#FXML
public void previewEmail() {
this.webEngine = this.previewWebView.getEngine();
this.webEngine.loadContent(this.messageEditor.getHtmlText());
}
#FXML
public void sendEmail() {
this.sendTaskProgressIndicator.setProgress(0.3D);
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("EmailSender");
primaryStage.setScene(viewLoaderService.loadViewOnScene("EmailSender"));
primaryStage.setResizable(false);
primaryStage.show();
}
}
File Reader Service
package emailsender.services;
import configuration.ProjectConfiguration;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javafx.stage.FileChooser;
/**
*
* #author DJava
*/
public class FileReaderService {
private final ProjectConfiguration configuration;
private final FileChooser fileChooser;
public FileReaderService(ProjectConfiguration configuration) {
this.configuration = configuration;
this.fileChooser = new FileChooser();
}
public String getFileText() {
String text = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(this.fileChooser.showOpenDialog(this.configuration.getStage())));
String line;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
} catch (IOException event) {
event.printStackTrace();
}
System.out.println(text);
return text;
}
}
Error
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8413)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:394)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$353(GlassViewEventHandler.java:432)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:431)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
... 49 more
Caused by: java.lang.NullPointerException
at emailsender.controllers.EmailSenderController.addHtml(EmailSenderController.java:77)
... 59 more
The problem is the controller that executes the addHtml method and the one you initially create is not the same. When you load the EmailSender, the FXMLLoader uses the empty constructor to create a new controller. Hence the constructor which sets the attributes is not called and you end up with null attributes.
To get the correct controller, use the loader's getController method and set the attributes with appropriate set methods:
FXMLLoader loader = new FXMLLoader("fxml file") ;
loader.load();
EmailSenderController controller = (EmailSenderController) loader .getController() ;
controller.setFileReadService(frs) ; // frs created elsewhere
On another note, your class architecture is a bit weird. You should only have one Application class. A controller should never be an application class. Its job is to control a view, not to run an entire window. As a suggestion, change your configuration to load the views and controllers as shown above. The controller attributes must be set right after loading the views.
Then in your EmailSender start method, simply load the view you want to be shown first before the end of the method.
EDIT
The reason your ViewLoaderService currently works is the way you set up your program, and illustrates why a controller shouldn't be an application. You create an instance of the controller with attributes. Then you instruct the controller to load the view (coincidentally the very view it represents). On the load of the view a new instance of the controller is created with its empty constructor (hence the null values). This new controller then acts as the controller for the displayed view, not the one you created at the start of the application.
When I call the login method in the LoginViewController class I receive a NullPointerException. I know that the user object is not null since it prints out the object with a toString. Do I have to register the Client and User class in the LoginView.fxml in some way? What Im trying to achieve is that when the user clicks on login the method should instantiate a new Client which sends the User object to the server.
Exception
User: Username Password
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8411)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:380)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:294)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:416)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
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)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
... 48 more
Caused by: java.lang.NullPointerException
at dinnerTime.Client.sendToServer(Client.java:44)
at dinnerTime.LoginViewController.login(LoginViewController.java:34)
... 58 more
Main.java
package dinnerTime;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Main extends Application {
private Stage primaryStage;
private BorderPane mainLayout;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
showLoginView();
}
private void showLoginView() throws IOException {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("LoginView.fxml"));
mainLayout = loader.load();
Scene scene = new Scene(mainLayout, 540, 400);
primaryStage.setScene(scene);
primaryStage.setResizable(false);
primaryStage.show();
}
}
LoginViewController.java
package dinnerTime;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
public class LoginViewController {
#FXML
private Main main;
#FXML
private TextField username;
#FXML
private PasswordField password;
#FXML
private Button login;
#FXML
private Button register;
private Client client;
private User user;
#FXML
public void login() throws IOException {
client = new Client("127.0.0.1", 3250);
client.start();
user = new User(username.getText(), password.getText());
System.out.println("User: " + user.toString());
client.sendToServer(user);
}
}
LoginView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.text.Font?>
<BorderPane prefHeight="400.0" prefWidth="540.0" xmlns="http://javafx.com/javafx/8.0.102" xmlns:fx="http://javafx.com/fxml/1" fx:controller="dinnerTime.LoginViewController">
<center>
<AnchorPane prefHeight="400.0" prefWidth="540.0" BorderPane.alignment="CENTER">
<children>
<ImageView fitHeight="122.0" fitWidth="124.0" layoutX="238.0" layoutY="14.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="#../../images/dt-logo-original.png" />
</image>
</ImageView>
<Label layoutX="14.0" layoutY="14.0" text="Dinner" textFill="#464646">
<font>
<Font size="70.0" />
</font>
</Label>
<Label layoutX="372.0" layoutY="14.0" text="Time" textFill="#464646">
<font>
<Font size="70.0" />
</font></Label>
<Label layoutX="91.0" layoutY="155.0" text="Username" />
<TextField layoutX="164.0" layoutY="151.0" prefHeight="25.0" prefWidth="216.0" />
<Label layoutX="91.0" layoutY="213.0" text="Password" />
<PasswordField layoutX="164.0" layoutY="209.0" prefHeight="25.0" prefWidth="216.0" />
<Button fx:id="login" layoutX="162.0" layoutY="271.0" mnemonicParsing="false" onAction="#login" prefHeight="59.0" prefWidth="216.0" text="Login" />
<Button layoutX="242.0" layoutY="352.0" mnemonicParsing="false" text="Register" />
</children>
</AnchorPane>
</center>
</BorderPane>
Client.java
package dinnerTime;
import java.io.*;
import java.net.*;
public class Client extends Thread {
private String ip;
private int port;
private Socket socket;
private ObjectOutputStream oos;
private ObjectInputStream ois;
public Client(String ip, int port) {
this.ip = ip;
this.port = port;
}
public void run() {
try {
socket = new Socket(ip, port);
oos = new ObjectOutputStream(socket.getOutputStream());
oos.flush();
ois = new ObjectInputStream(socket.getInputStream());
while (true) {
try {
Object obj = ois.readObject();
if (obj instanceof Recipe) {
}
} catch (IOException | ClassNotFoundException e) {
}
}
} catch (IOException e) {
}
}
public void sendToServer(Object obj) {
try {
oos.writeObject(obj);
oos.flush();
} catch (IOException e) {
}
}
}
User.java
package dinnerTime;
import java.io.Serializable;
public class User implements Serializable {
private String name, password;
public User(String name, String password){
this.name = name;
this.password = password;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return name + " " + password;
}
}
You have a race condition on the client's oos field. You initialize it in the run() method, which is executed on the background thread, but you try to access it in sendToServer() which is called from login() in the controller, and executed on the FX Application Thread.
Because these are on different threads, there is no guarantee as to which will be executed first: what is happening is that sendToServer() is getting executed before the background thread initializes oos, and hence oos.writeObject(...) is throwing a null pointer exception.
To fix this, you need to ensure that you do not call sendToServer() until the client is fully connected. One approach is to provide a callback of some kind to execute when the connection is established:
public class Client extends Thread {
private String ip;
private int port;
private Socket socket;
private ObjectOutputStream oos;
private ObjectInputStream ois;
private Runnable onConnected ;
public void setOnConnected(Runnable onConnected) {
this.onConnected = onConnected ;
}
public Client(String ip, int port) {
this.ip = ip;
this.port = port;
}
public void run() {
try {
socket = new Socket(ip, port);
oos = new ObjectOutputStream(socket.getOutputStream());
oos.flush();
if (onConnected != null) {
onConnected.run();
}
ois = new ObjectInputStream(socket.getInputStream());
while (true) {
try {
Object obj = ois.readObject();
if (obj instanceof Recipe) {
}
} catch (IOException | ClassNotFoundException e) {
}
}
} catch (IOException e) {
}
}
public void sendToServer(Object obj) {
try {
oos.writeObject(obj);
oos.flush();
} catch (IOException e) {
}
}
}
and then
#FXML
public void login() throws IOException {
client = new Client("127.0.0.1", 3250);
user = new User(username.getText(), password.getText());
client.setOnConnected(() -> client.sendToServer(user));
client.start();
}
I am having an issue with my code where whenever I try to do something more than once, the program will crash on me. For example, if I login, then log out and then log back in for a second time, the program will crash. This is happening for other things that I want to do more than once such as switching to another scene, going back to home then trying to go to the other scene again.
Will just post the code for the login part.
Main
package libraryapp;
import java.io.File;
import java.io.IOException;
import java.util.prefs.Preferences;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import libraryapp.model.Book;
import libraryapp.model.BookListWrapper;
import libraryapp.view.BrowseController;
import libraryapp.view.HomeOverviewController;
import libraryapp.view.LoginController;
import libraryapp.view.RootLayoutController;
public class LibraryApp extends Application {
private Stage primaryStage;
private BorderPane rootLayout;
/**
* The data as an observable list of Books.
*/
private ObservableList<Book> bookData = FXCollections.observableArrayList();
/**
* Constructor
*/
public LibraryApp() {
// Add some sample data
bookData.add(new Book("Hans", "Muster"));
bookData.add(new Book("Ruth", "Mueller"));
bookData.add(new Book("Heinz", "Kurz"));
bookData.add(new Book("Cornelia", "Meier"));
bookData.add(new Book("Werner", "Meyer"));
bookData.add(new Book("Lydia", "Kunz"));
bookData.add(new Book("Anna", "Best"));
bookData.add(new Book("Stefan", "Meier"));
bookData.add(new Book("Martin", "Mueller"));
}
/**
* Returns the data as an observable list of Books.
* #return
*/
public ObservableList<Book> getBookData() {
return bookData;
}
#Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("LibraryApp");
initRootLayout();
showLogin();
}
/**
* Initializes the root layout and tries to load the last opened
* person file.
*/
public void initRootLayout() {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(LibraryApp.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
// Give the controller access to the main app.
RootLayoutController controller = loader.getController();
controller.setLibraryApp(this);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
// Try to load last opened person file.
File file = getBookFilePath();
if (file != null) {
loadBookDataFromFile(file);
}
}
/**
* Shows the home overview inside the root layout.
*/
public void showHomeOverview() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(LibraryApp.class.getResource("view/HomeOverview.fxml"));
AnchorPane homeOverview = (AnchorPane) loader.load();
// Set home overview into the center of root layout.
rootLayout.setCenter(homeOverview);
// Give the controller access to the main app.
HomeOverviewController controller = loader.getController();
controller.setLibraryApp(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showLogin() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(LibraryApp.class.getResource("view/Login.fxml"));
AnchorPane login = (AnchorPane) loader.load();
// Set home overview into the center of root layout.
rootLayout.setCenter(login);
// Give the controller access to the main app.
LoginController controller = loader.getController();
controller.setLibraryApp(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showBrowse() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(LibraryApp.class.getResource("view/Browse.fxml"));
AnchorPane browse = (AnchorPane) loader.load();
// Set browse into the center of root layout.
rootLayout.setCenter(browse);
// Give the controller access to the main app.
BrowseController controller = loader.getController();
controller.setLibraryApp(this);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Returns the main stage.
* #return
*/
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
Application.launch(args);
}
Login Controller
package libraryapp.view;
import java.io.File;
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.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import libraryapp.LibraryApp;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* FXML Controller class
*
* #author Michael
*/
public class LoginController implements Initializable {
/**
* Initializes the controller class.
*/
#FXML
private AnchorPane loginPane;
#FXML
private Label lblMessage;
#FXML
private TextField txtUsername;
#FXML
private PasswordField txtPassword;
private LibraryApp libraryApp;
public String getString(String tagName) throws SAXException, IOException, ParserConfigurationException{
File file = new File("src/libraryapp/account.xml");
DocumentBuilderFactory docBuildFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuildFactory.newDocumentBuilder();
Document document = docBuilder.parse(file);
NodeList list = document.getElementsByTagName(tagName);
if (list != null && list.getLength() > 0){
NodeList subList = list.item(0).getChildNodes();
if (subList != null && subList.getLength() > 0) {
return subList.item(0).getNodeValue();
}
}
return null;
}
#FXML
private void login(ActionEvent event) throws IOException, ParserConfigurationException, SAXException {
String email = getString("email");
String password = getString("password");
if (txtUsername.getText().equals(email) && txtPassword.getText().equals(password)){
libraryApp.showHomeOverview();
} else{
lblMessage.setText("Username or password invalid!");
}
}
#FXML
private void register(ActionEvent event) throws IOException {
AnchorPane pane = FXMLLoader.load(getClass().getResource("Register.fxml"));
loginPane.getChildren().setAll(pane);
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void setLibraryApp(LibraryApp libraryApp) {
this.libraryApp = libraryApp;
}
}
And this is the error that I get
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8413)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
... 52 more
Caused by: java.lang.NullPointerException
at libraryapp.view.LoginController.login(LoginController.java:82)
... 62 more
Logout
#FXML
public void logout(ActionEvent event) throws IOException {
File bookFile = libraryApp.getBookFilePath();
libraryApp.saveBookDataToFile(bookFile);
AnchorPane pane = FXMLLoader.load(getClass().getResource("Login.fxml"));
browsePane.getChildren().setAll(pane);
}
Your implementation of logout() loads the login fxml file again, but does not set the libraryApp field on the new controller. Consequently, that field is null in that instance of the controller, and you get a null pointer exception.
Since you already have a reference to the libraryApp, you can reuse the existing code to load the login screen simply by calling
libraryApp.showLogin();