我正在开发一个客户机-服务器信使应用程序进行实践。在我的客户端模块中有client类、ClientController类、ClientGUI类和fxml文件、Message类、CSS文件和Main类。我在我的ClientGUI类和ClientController类中有一个方法,display(String message),它将message对象添加到id为#messages的VBox中。
这是我的问题:在我的ClientController类内部是一个display()方法,它调用ClientGUI的display()方法(我知道这似乎是多余的,但这不是问题)。当display()方法在我的ClientGUI类中被调用时,例如在setOnMouseClick()方法中,它可以正常工作。然而,当从我的ClientController类调用此方法时,我得到一个NullPointerException,指向我的ClientGUI类的display()方法中VBox类型的消息变量。我已经尝试用VBox test = messages;
替换messages.getChildren().add(new Message(message));
后者工作正常,而前者抛出异常。我还尝试在我的消息变量上调用其他方法,所有这些方法都会抛出相同的错误。为什么会发生这种情况?
(它仍在开发过程中,因此可能有其他不相关的问题)
客户:package client;
import java.io.*;
import java.net.Socket;
/**
* Gabe
* 9/26/2016
* Description: Represents client and its socket
*/
public class Client implements Serializable {
private static Client instance;
private Socket clientSocket;
private BufferedReader in;
private PrintWriter out;
private ObjectOutputStream objectOutputStream;
private boolean connected = false;
private static final long serialVersionUID = 0L;
private Client() {}
public void connect(String targetAddress, String username_, int port_) {
try {
clientSocket = new Socket(targetAddress, port_);
clientSocket.setReuseAddress(true); // Allows same port to be used successively without cool-down
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
objectOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());
objectOutputStream.writeObject(username_);
ClientController.getInstance().display("Attention: Successfully connected to server");
connected = true;
} catch (IOException e) {
ClientController.getInstance().display("Attention: Unable to connect to server");
}
}
public void disconnect() {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (objectOutputStream != null) {
objectOutputStream.close();
}
if (clientSocket != null) {
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
connected = false;
}
public boolean connected() {
return connected;
}
public static Client getInstance() {
if (instance == null) {
instance = new Client();
}
return instance;
}
public void sendMessage(String message) {
out.println(message);
}
}
ClientController:
package client;
import javafx.scene.layout.VBox;
/**
* Gabe Castelli
* 9/28/2016
* Description:
*/
public class ClientController implements Controller {
private static ClientController instance;
private ClientController() {}
public static ClientController getInstance() {
if (instance == null) {
instance = new ClientController();
}
return instance;
}
// Controls
public void display(String message) {
ClientGUI.getInstance().display(message);
}
public void displayAndSend(String message) {
display(message);
Client.getInstance().sendMessage(message);
}
public void connect(String address_, String username_, int port_) {
Client.getInstance().connect(address_, username_, port_);
}
public void disconnect() {
Client.getInstance().disconnect();
}
}
ClientGUI:
package client;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
* Gabe Castelli
* 9/26/2016
* Description: GUI for client-side using JavaFX
*/
public class ClientGUI extends Application {
private Scene scene;
private TextField targetAddress;
private TextField fieldUsername;
private TextField fieldPort;
private VBox messages;
private TextField input;
private Button btnConnect;
private String username = "Anonymous";
private int port = 2000;
private static ClientGUI instance;
public static ClientGUI getInstance() {
if (instance == null) {
instance = new ClientGUI();
}
return instance;
}
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("ClientGUI.fxml"));
scene = new Scene(root, 480, 360);
stage.setTitle("MyMessenger");
stage.setScene(scene);
stage.setMinWidth(660);
stage.setMinHeight(495);
stage.setMaxWidth(990);
stage.show();
targetAddress = (TextField) scene.lookup("#targetAddress");
fieldUsername = (TextField) scene.lookup("#fieldUsername");
fieldPort = (TextField) scene.lookup("#fieldPort");
messages = (VBox) scene.lookup("#messages");
input = (TextField) scene.lookup("#input");
btnConnect = (Button) scene.lookup("#btnConnect");
input.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.ENTER) {
if (Client.getInstance().connected()) {
ClientController.getInstance().displayAndSend(input.getText());
input.setText("");
} else {
display("Attention: Not connected to server");
input.setText("");
}
}
});
btnConnect.setOnMouseClicked(event -> {
if (!Client.getInstance().connected()) {
if (!targetAddress.getText().equals("")) {
if (!fieldUsername.getText().equals("")) {
username = fieldUsername.getText();
}
if (!fieldPort.getText().equals("")) {
port = Integer.valueOf(fieldPort.getText());
}
ClientController.getInstance().connect(targetAddress.getText(), username, port);
btnConnect.setText("Disconnect");
} else {
display("Attention: Address required");
}
} else {
ClientController.getInstance().disconnect();
display("Attention: Disconnecting...");
btnConnect.setText("Connect");
}
});
}
public void display(String message) {
messages.getChildren().add(new Message(message));
}
}
堆栈跟踪:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at client.ClientGUI.display(ClientGUI.java:96)
at client.ClientController.display(ClientController.java:26)
at client.Client.connect(Client.java:34)
at client.ClientController.connect(ClientController.java:35)
at client.ClientGUI.lambda$start$1(ClientGUI.java:81)
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.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$ClickGenerator.postProcess(Scene.java:3470)
at javafx.scene.Scene$ClickGenerator.access$8100(Scene.java:3398)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3766)
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:352)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$355(GlassViewEventHandler.java:388)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:387)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
空指针异常正在发生,因为您从ClientGUI.getInstance()
获得的ClientGUI
实例不是作为JavaFX启动过程的一部分创建的实例,并且在其上调用start()
方法。因为messages
是在start()
中初始化的,所以从ClientGUI.getInstance()
获得的实例没有初始化messages
。所以当你调用ClientGUI.getInstance().display(message)
时,它调用messages.getChildren()...
: messages
在ClientGUI
实例中是空的,你会得到一个空指针异常。
这里的潜在问题是整体结构。您确实不能创建这些单例—特别是Application
子类—因为它们是由框架实例化的。ClientGUI
是由JavaFX启动进程实例化的,而使用FXMLLoader
的方式,ClientController
是由FXMLLoader.load()
实例化的(所以ClientController.getInstance()
可能也没有给你所希望的实例)。
这不是很清楚,当然没有意义,为什么你试图使这些类的单例。我的猜测是,你正试图绕过你现有的结构,这是完全不标准的。你所定义的方法几乎都在类中,这些类不应该对这些方法实现的功能负责。
特别地:Application
子类负责应用程序生命周期。它应该有一个start
方法,它只是加载初始视图(FMXL文件),把它放在一个窗口中,然后显示它。如果您有/需要其他服务,它也可能启动它们。如果需要,它可以选择覆盖init()
和stop()
。
控制器类负责更新视图。这是您应该引用FXML文件中定义的UI控件的唯一地方,也是您应该修改显示的唯一地方。
模型类(Client
)应该完全不知道视图或控制器。它应该只表示正在呈现的状态或数据。这是控制器的责任(实际上是一个呈现者,在其他一些体系结构中这可以由视图完成)根据模型所表示的数据来更新视图。
因此,您可能希望按照以下方式重构应用程序。这取决于您可能需要的其他东西,但这至少应该让您进入一个可行的轨道:
ClientGUI:
public class ClientGUI extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("ClientGUI.fxml"));
scene = new Scene(root, 480, 360);
stage.setTitle("MyMessenger");
stage.setScene(scene);
stage.setMinWidth(660);
stage.setMinHeight(495);
stage.setMaxWidth(990);
stage.show();
}
}
ClientController:
public class ClientController implements Controller {
@FXML
private TextField targetAddress;
@FXML
private TextField fieldUsername;
@FXML
private TextField fieldPort;
@FXML
private VBox messages;
@FXML
private TextField input;
@FXML
private Button btnConnect;
private String username = "Anonymous";
private int port = 2000;
private Client client ;
public void initialize() {
client = new Client();
}
@FXML
private void connect() {
if (!client.connected()) {
if (!targetAddress.getText().equals("")) {
if (!fieldUsername.getText().equals("")) {
username = fieldUsername.getText();
}
if (!fieldPort.getText().equals("")) {
port = Integer.valueOf(fieldPort.getText());
}
try {
client.connect(targetAddress.getText(), username, port);
btnConnect.setText("Disconnect");
display("Attention: Successfully connected to server");
} catch (IOException exc) {
display("Attention: Unable to connect to server");
}
} else {
display("Attention: Address required");
}
} else {
client.disconnect();
display("Attention: Disconnecting...");
btnConnect.setText("Connect");
}
}
@FXML
private void message() {
if (client.connected()) {
displayAndSend(input.getText());
input.setText("");
} else {
display("Attention: Not connected to server");
input.setText("");
}
}
public void display(String message) {
messages.getChildren().add(new Message(message));
}
public void displayAndSend(String message) {
display(message);
client.sendMessage(message);
}
}
然后
// Note: why on earth is this Serializable? What state are you intending to serialize???
public class Client implements Serializable {
private Socket clientSocket;
private BufferedReader in;
private PrintWriter out;
private ObjectOutputStream objectOutputStream;
private boolean connected = false;
private static final long serialVersionUID = 0L;
public void connect(String targetAddress, String username_, int port_) throws IOException {
clientSocket = new Socket(targetAddress, port_);
clientSocket.setReuseAddress(true); // Allows same port to be used successively without cool-down
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
objectOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());
objectOutputStream.writeObject(username_);
connected = true;
}
public void disconnect() {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (objectOutputStream != null) {
objectOutputStream.close();
}
if (clientSocket != null) {
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
connected = false;
}
public boolean connected() {
return connected;
}
public void sendMessage(String message) {
out.println(message);
}
}
要使控制器工作,需要根元素定义一个fx:controller="client.ClientController"
属性,ClientGUI.fxml
中的控件定义与控制器类中的字段名称匹配的fx:id
属性,并指定事件处理程序方法,例如:
<!-- ... -->
<TextField fx:id="targetAddress" />
<TextField fx:id="fieldUserName" />
<TextField fx:id="fieldPort" />
<VBox fx:id="messages" />
<TextField fx:id="input" onAction="#message" />
<Button text="Connect" fx:id="btnConnect" onAction="#connect" />
<!-- ... -->
(注意,当按enter键时,文本字段会触发一个ActionEvent
,因此不需要打乱按下键的处理程序等)
你可能需要稍微修改一下,以使应用程序的其余功能正常工作,但只要你坚持基本原则:只有控制器应该修改UI;Client
类应该不了解演示细节等,那么您将走上正确的道路。如果你让任何 static
,当然,如果你试图做任何这些单例,你做错了。