I'm trying to put the alphabet in different buttons, but I cant make it work. My code looks like this:
char[] Letter = {'a','b','c','d','e','f','g','h'
,'i','j','k','l','m','n','o','p','q'
开发者_Python百科 ,'r','s','t','u','v','w','x','y','z'};
Button[] But;
for (int i = 0; i <= 26; ++i) {
But = new Button(Letter[i]);
this.add(But[i], BorderLayout.SOUTH);
}
This should work for you. Its convention in Java to name variables starting with a lower case letter.
char[] letters = {'a','b','c','d','e','f','g','h'
,'i','j','k','l','m','n','o','p','q'
,'r','s','t','u','v','w','x','y','z'};
Button[] buttons = new Button[26];
for(int i = 0;i< 26;++i){
buttons[i] = new Button(Character.toString(letters[i])); //need to convert char to String first
this.add(buttons[i],BorderLayout.SOUTH);
}
char[] letters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for(char c : letters) add(new JButton(new String(c)));
You probably wanted this
But[i] = new Button(Letter[i]);
instead of this
But = new Button(Letter[i]);
精彩评论