通过数组

时间:2015-12-07 17:29:18

标签: java arrays swing loops methods

对于我必须提交的项目,我要建立一个多线程的客户端 - 服务器聊天。在这个项目的一部分。我有一个服务器使用ObjectOutputStream的.writeObject()方法传递一个数组,如下所示:

public void sendOnline(){
    try{
        //send the array of currently online users to the client
        serverOutputStream.writeObject(loggedOn);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

(其中loggedOn是一个包含4个元素的Boolean []数组,指示哪个用户已使用与该数组对应的参与者编号登录。)

然后客户端收到这个数组(首先我将在客户端类的顶部显示声明)

String[] onlineUsers = new String[]{"Arken", "Ben", "Darklark", "Free"};
Boolean[] online = new Boolean[]{false, false, false, false}; // this array will store details of who is online
Boolean[] sendTo = new Boolean[]{false,false,false,false}; //array to hold which user will receive a message
JToggleButton[] buttons = new JToggleButton[]{btnArken, btnBen, btnDarklark, btnFree}; // this will be used with the online array to enable buttons

然后客户端中导致我出现问题的代码来自一个在收到数组时调用的方法:

public void getUsersOnline(){
    try {
        online = (Boolean[]) clientInputStream.readObject();
        int noOfUsers = 0;
        for(int i = 0; i < buttons.length; i++){
            if(online[i] == true && i != participantNo){
                buttons[i].setEnabled(true); //nullpointerexception
                noOfUsers ++;
            }
            addBroadcast("You have " + (noOfUsers - 1) + " friends online!"); //display number of users online, except for the client itself

            for(int j = 0; j < online.length; j++){
                if(online[j] && j != participantNo){
                    addBroadcast(onlineUsers[i] + " is online");
                }
            }
        }
    } catch (ClassNotFoundException | IOException e) {
        // TODO Auto-generated catch block
        System.out.println(e);
        System.exit(1);

我在这里尝试做的是迭代按钮数组,如果在线数组中相同位置的元素为真,则启用按钮。 (它们都是相同的长度)但是由于某种原因,我在.setEnabled行得到了NullPointerException,并且我尝试过的任何东西都没有解决它。由于catch语句代码可以继续,但按钮不起作用。有什么建议吗?

谢谢!

0 个答案:

没有答案