Java 通过数组启用JTogglebuttons
对于一个我必须提交的项目,我正在构建一个多线程的客户机-服务器聊天系统。在这个项目的一部分。我让服务器使用ObjectOutputStream的.writeObject()方法传递数组,如下所示:Java 通过数组启用JTogglebuttons,java,arrays,swing,loops,methods,Java,Arrays,Swing,Loops,Methods,对于一个我必须提交的项目,我正在构建一个多线程的客户机-服务器聊天系统。在这个项目的一部分。我让服务器使用ObjectOutputStream的.writeObject()方法传递数组,如下所示: public void sendOnline(){ try{ //send the array of currently online users to the client serverOutputStream.writeObject(loggedOn);
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个元素组成的布尔[]数组,表示哪个用户已登录,其参与者编号对应于该数组。)
然后客户机接收这个数组(首先我将在客户机类的顶部显示声明)
然后,客户端中导致我出现问题的代码位于一个方法之下,该方法在接收阵列时被调用:
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);
public void getUsersOnline(){
试一试{
online=(布尔[])clientInputStream.readObject();
int noOfUsers=0;
对于(int i=0;i
我在这里要做的是迭代buttons数组,如果在线数组中相同位置的元素为true,则启用button。(它们的长度相同)但是由于某种原因,我在.setEnabled行遇到了一个NullPointerException,我尝试过的任何方法都无法解决它。由于catch语句,代码可以继续,但按钮不起作用。有什么建议吗
谢谢!您尚未在
按钮中初始化JToggleButton
的实例,这些按钮是btnArken、btnBen、btnDarklark、btnFree
的副本?可能您没有初始化按钮数组中的4个按钮??btn Name-只是聊天服务相关用户的按钮。JToggleButtons已初始化它们在登录后调用的GUI构造函数中初始化
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);