I am working on a messaging application. The GUI is written in Java Swing. When the client starts, it asks my server for the chats a specific user is involved in. The server will send these in the form of an string array eg: {CHAT_PATH,CHAT_PATH}.
Once the client receives this it feeds it to my GUI class, which is supposed to display each chat name in the list (I will filter out the rest of the path) on screen listed downward. This is where my problem lies. I start by creating a JButton list:
JButton[] chat_names = {};
and then I loop through the list of chats (chat_data) and add to my chat_names list a new JButton for each chat name. Like this:
for (int x=0; x<chat_data.length-1; x++){
chat_names[x] = new JButton(chat_data[x]);
chat_names[x].setBounds(100,100,100,100);
}
for (int x=0; x<chat_names.length; x++){
frame.add(chat_names[x]);
}
When I do this I get the following syntax error:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: Index 0 out of
bounds for length 0
at gui_main.menu_screen(gui_main.java:16)
at Main.main(Main.java:89)
Does anyone know if this is fixable or another way I could display a list of buttons each with a chat_name on them.
JButton[] chat_names = {};Here you created an array ofJButtonswith length 0, you can either callchat_names = new JButton[chat_data.length];before thefor-loopsor create aList<JButton> chatNames = new ArrayList<>()to have a variable length list of buttons, and as a tip usecamelCaserather thansnake_casefor your variables and methods, as that's the convention. And one more thing don't manually specify the bounds of eachJButton, instead use a proper Layout Managerfor-loopsand include this line inside the first loop:frame.add(chat_names[x]);