0

I have a swing application which I have declared a JButton array inside it's constructor inside that class I have created a for loop in order to add a number of 114 JButton to class container.

but when that class runs it gives the exception

java.lang.ArrayIndexOutOfBoundsException: 0

On the statement that adding the Buttons to Container.

Can someone see the problem?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main extends JFrame implements ActionListener
{
   public Main()
   {
      Container pane = getContentPane();
      JPanel panel = new JPanel();
      JButton b[];
      int i;

      for (i = 0; i < 114; i++)
      {
         b = new JButton[i];
         panel.add(b[i]);
      }
      pane.add(panel);
   }

   public void actionPerformed(ActionEvent ae)
   {
   }

   public static void main(String[] args)
   {
      Main m = new Main();
      m.setSize(500, 500);
      m.setVisible(true);
   }
}

3 Answers 3

3

You can't made expression like that

for(i=0; i<114;i++)
{
 b  = new JButton[i];
 panel.add(b[i]);
}

In first execution it is new JButton[0], so your array size is 0.

You should use Collection (fe. ArrayList) or fixed size JButton array.

JButton[] b  = new JButton[114];
for(i=0; i<114;i++)
{
 b[i]  = new JButton();
 panel.add(b[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

2

At i = 0, b = new JButton[i]; creates an array of size 0, so trying to reference b[0] (i.e. the first element) will be out of bounds.

And you never construct b[i].

You probably want to move the array construction outside the loop, something like:

b = new JButton[114];
for (i = 0; i < 114; i++)
{
   b[i] = new JButton();
   panel.add(b[i]);
}

Comments

0

since b is an array type which holding collection of JButton objects.So you need to create one JButton object for each location of that array. The code what Dukeling is given is correct approach. And also one thing you have forgotten,You need to define the size of your array like JButton b[]=new JButton[size];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.