0

So Im trying to challenge myself and create a simple word processor application. I'm currently setting up the keyboard and having some trouble with the keys. I have a String array with each of the letters of the alphabet and want to place them onto the buttons.

I have this at the moment:

    String FirstRow [] = {"q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"};

    for(int i = 0; i < 40; i++)
    {
        if(i < 10)
        {
            JButton btn = new JButton();
            Nums.add(btn);
            btn.setText("" + Num);
            Num++;
        }
        else
        {       
            JButton btn1 = new JButton ();
            Nums.add(btn1);
            btn1.setText("" + FirstRow[n]);
            n++;
        }
    }

Without the else section of the if statement it works fine placing numbers into the first row. When I try to place the letters however, I get an out of bounds exception and Im not sure how to fix this.

mKorbel
  • 109,525
  • 20
  • 134
  • 319

3 Answers3

2

Yor array only contains 26 elements but your loop goes up to 39. So when your for-loop reaches the count of 26 (arrays are zero indexed) you'll get the ArrayIndexOutOfBoundsException.

Christian
  • 21
  • 1
2

An out of bounds exception means that you're trying to access an index that is larger than the array can hold. Try using foreach instead: How does the Java 'for each' loop work?

Or try for(int i = 0; i < your_array.length; i++)

Community
  • 1
  • 1
Rafael Khan
  • 136
  • 3
2

You should make your virtual keyboard a 2 dimensional array:

String[][] keyCaps = {{"`", "1", ..., "0", "-", "="},
                      {"q", "w", ..., "p", "[", "]", "\\"},
                      ...,
                      {"z", "x", ..., "m", ",", ".", "/"}};

And then,

for (String[] row: keyCaps) {
    for (String key: row) {
        // create button.
        // Add button to layout.
    }
    // Go to next row on screen.
}

You can choose a different array based on the locale, of course. If the locale is French, you probably want a French AZERTY (?) keyboard. Is AZERTY correct?

Eric Jablow
  • 7,874
  • 2
  • 22
  • 29