I have been working on this problem for a couple of days and I cannot understand where I went wrong. I have created a Server-Client Chat Program and on the Server GUI there is a tab that shows a list of users. This list works in every way that I want. I wanted to add a UserList
to the Client GUI and the JList
is there, but when I update the DefaultListModel
, the JList
only updates on the ServerGUI
. I tried to debug and found that the JList
on the ChatGUI is not displayable and I don't know why, or how to fix it.
Here is my (relevant) code:
Client Class
public class Client {
String username;
Socket socket;
PrintWriter out;
Scanner in;
public Client (String username, Socket socket, PrintWriter out, Scanner in) {
this.username = username;
this.socket = socket;
this.out = out;
this.in = in;
}
}
ServerGUI Class - (the register method is called later in the program when a Client joins)
public class ServerGUI {
public volatile static ArrayList<Client> users;
public static DefaultListModel<String> model = new DefaultListModel<String>();
static Client clientReg;
public static void register(Client client) {
clientReg = client;
users.add(clientReg);
model.addElement(clientReg.username);
ServerView.userList.setModel(model);
ChatView.userList.setModel(model);
}
}
ChatView Class
public class ChatView extends JFrame {
public JPanel contentPane;
public static JList<String> userList = new JList<String>();
public static JTextArea chatOutput;
private JTextField inputField;
public ChatView() {
setResizable(false);
setTitle("Chat GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 475);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane tabs = new JTabbedPane(JTabbedPane.TOP);
tabs.setBounds(0, 0, 535, 435);
contentPane.add(tabs);
JPanel chatViewer = new JPanel();
tabs.addTab("Chat", null, chatViewer, null);
chatViewer.setLayout(null);
// Code that makes up the chatViewer JPanel
JPanel userListPane = new JPanel();
tabs.addTab("User List", null, userListPane, null);
userListPane.setLayout(null);
JLabel label = new JLabel("User List:");
label.setBounds(10, 10, 510, 20);
userListPane.add(label);
userList.setModel(new AbstractListModel<String>() {
public String getElementAt(int index) {
return ServerGUI.model.get(index);
}
public int getSize() {
return ServerGUI.model.size();
}
});
userList.setValueIsAdjusting(true);
userList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
userList.setBounds(10, 40, 510, 395);
userListPane.add(userList);
}
}
Most of my programming has been self taught so if there is any format that is incorrect please let me know so that I may be able to correct it.