我正在构建一个javafx项目,我面临下面列出的一些问题。
首先,当我没有在构造函数sfc = new ServerFrameController();
&中初始化2个类时,我得到了NullPointerException。 sf = new ServerFrame();
。即使在搜索了几个小时后,我也无法找出空指针异常的原因。然后我想也许初始化类可能会有所帮助。但在添加这两行后,我得到了InvocationTargetException
。请帮忙!!
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)
第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.....
}
第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();
}
}
答案 0 :(得分:0)
您可以通过将StackOverflowError
的引用传递给控制器来避免ServerFrame
的问题,但一般来说,从构造函数中传递this
的引用是不好的做法。
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.....
}
最好的可能是找出NullPointerException并找到适当的解决方案。我猜这是以某种方式与所有初始化的顺序相关。