Home > OS >  Append swing jbutton elements to array in java
Append swing jbutton elements to array in java

Time:12-23

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.

CodePudding user response:

Here you created an array of JButtons with length 0

JButton[] chat_names = {};

You can either call

chat_names = new JButton[chat_data.length]; 

before the for-loops or create a

List<JButton> chatNames = new ArrayList<>();

to have a variable length list of buttons

As a tip use camelCase rather than snake_case for your variables and methods, as that's the convention.

And one more thing don't manually specify the bounds of each JButton, instead use a proper Layout Manager for example GridLayout or BoxLayout may work. If you insist on using setBounds and (more than surely) null-layout you may find yourself in a problem similar to this one when trying to run it on a different computer or a different monitor.

You can also merge these 2 loops:

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]);
}

Into one, reducing one iteration over all the chats and thus improving performance:

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); //Use a layout manager!
    frame.add(chat_names[x]);
}
  • Related