I am building a javafx project in which I am facing some problems listed below.
First, I was getting a NullPointerException when i was not initializing the 2 classes in constructor sfc = new ServerFrameController();
& sf = new ServerFrame();
.Even after searching for hours, I was not able to figure out the cause for the null pointer exception. Then i thought maybe initializing the classes might help. But After adding these two lines I am getting InvocationTargetException
. Please help!!
Exception in Application constructor
java.lang.reflect.InvocationTargetException
Caused by: java.lang.StackOverflowError
at com.socket.ServerFrameController.<init>(ServerFrameController.java:35)
at com.socket.ServerFrame.<init>(ServerFrame.java:28)
Class 1:
public class ServerFrame extends Application {
public ServerFrameController sfc;
public SocketServer server;
public Thread serverThread;
public String filePath = "D:\\Data.xml";
public JFileChooser fileChooser;
public JFXPanel fxPanel;
public ServerFrame() {
sfc = new ServerFrameController();
fxPanel = new JFXPanel();
fxPanel.setVisible(true);
fileChooser = new JFileChooser();
}
// Some More Code.....
}
Class 2:
public class ServerFrameController implements Initializable {
ServerFrame sf;
@FXML
public TextField jTextField3;
@FXML
public Button jButton2;
@FXML
public Button jButton1;
@FXML
public TextArea jTextArea1;
public ServerFrameController() {
sf = new ServerFrame();
}
}
You can avoid the issue of StackOverflowError
by passing a reference to the ServerFrame
to the controller, but in general it is bad practice to pass a reference of this
from within the constructor.
public class ServerFrameController implements Initializable {
ServerFrame sf;
@FXML
public TextField jTextField3;
@FXML
public Button jButton2;
@FXML
public Button jButton1;
@FXML
public TextArea jTextArea1;
public ServerFrameController(ServerFrame sf) {
this.sf = sf;
}
}
public class ServerFrame extends Application {
public ServerFrameController sfc;
public SocketServer server;
public Thread serverThread;
public String filePath = "D:\\Data.xml";
public JFileChooser fileChooser;
public JFXPanel fxPanel;
public ServerFrame() {
sfc = new ServerFrameController(this);
fxPanel = new JFXPanel();
fxPanel.setVisible(true);
fileChooser = new JFileChooser();
}
// Some More Code.....
}
Best would probably be to figure out the NullPointerException and find the proper solution for that. I would guess that is is somehow related to the order everything is initialized.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.