1

I am a beginner to programming. I'm a few weeks into my first programming class, so please bear with me. I am not a person to ask for help, so I have searched for an answer extensively with no luck. This is also my first time posting anything in any type of forum, so if my question structure is off I'm sorry and I will correct for future posts.

I found this problem while running my program.

  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
  at btn.Butto.<init>(Butto.java:23)
  at btn.Butto.main(Butto.java:34)
  Java Result: 1
  BUILD SUCCESSFUL

And this is the code I'm working on

  package btn;

    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;

   public class Butto extends JFrame implements ActionListener{
    JButton[] btn = new JButton[100];
    public Butto(){
    setSize(500, 500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("100 Button");
    FlowLayout fl =new FlowLayout();
    setLayout(fl);

    for (int i=1; i<=100;i++){
    btn[i] = new JButton();
    add(btn[i]);
    btn[i].setText("CLick"+i);
    btn[i].addActionListener(this);
      }        
    }
    public static void main(String[] args) {
    Butto bt = new Butto();
    bt.setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent e) {

      for(int j=1; j<btn.length; j++){
      if(e.getSource().equals(btn[j])){
        JOptionPane.showMessageDialog(null, "click"+j);
                }
             }
           }
       }

Thank you in advance for any help. I'm not looking to have this done for me, I'm just stuck and need help finding my way.

1 Answers1

1

The problem is with this part:

 for (int i=1; i<=100;i++){
    btn[i] = new JButton();
    add(btn[i]);
    btn[i].setText("CLick"+i);
    btn[i].addActionListener(this);
  }   

change the i<=100 to i < 100, You should also change the int i=1 to int i=0, as arrays start at 0, not 1.

With i<=100 you're counting from 0..100, but arrays are indexed from 0..length-1, so you need to count from 0..99 in your case.

Shaun Wild
  • 1,187
  • 3
  • 15
  • 33