我正在尝试使用与从服务器接收图标的多个客户端相关的回调。
到目前为止我的代码看起来像这样。 任何人都可以指出我正确的方向。当我尝试使用IconListener arraylist时,我得到一个NullPointerException。
package p2;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class P2Viewer extends JPanel {
private JLabel lblIcon = new JLabel();
private IconClient iconClient;
private IconManager iconManager;
public P2Viewer(int width, int height) {
setLayout(new FlowLayout(FlowLayout.CENTER));
lblIcon.setOpaque(true);
add(lblIcon);
setPreferredSize(new Dimension(width, height));
}
public P2Viewer(IconClient iconClient, int width, int height) {
this(width, height);
this.iconClient = iconClient;
this.iconClient.addIconListener(new Listener());
}
public void setIcon(Icon icon) {
lblIcon.setIcon(icon);
}
private class Listener implements IconListener {
@Override
public void Icon(Icon icon) {
if (icon instanceof Icon) {
setIcon(icon);
}
}
}
}
package p2;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.ArrayList;
import javax.swing.Icon;
public class IconClient extends Thread {
private Socket socket;
private ObjectInputStream ois;
private Icon icon;
private ArrayList<IconListener> iconlistener;
public IconClient(String ip, int port) {
try{
socket = new Socket(ip, port);
ois = new ObjectInputStream(socket.getInputStream());
start();
}catch(IOException e){
System.err.println(e);
}
}
public void addIconListener(IconListener iconListener) {
this.iconlistener.add(iconListener);
}
public void run() {
while (true) {
try {
icon = (Icon) ois.readObject();
System.out.println("Icon received");
for(IconListener iconList:iconlistener){
iconList.Icon(icon);
}
System.out.println("Icon sent to listener");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}