I have a word as string that want to take a character of it and assign it as the button name. As you know button only accepts String.
String possibleLetters = "asdaAsadWERWasdas";
for (int i = 0; i <= possibleLetters.length(); i++)
{
String bottonName = possibleLetters.charAt(i);
JButton letterBottons = new JButton(bottonName);
}
尝试:
JButton letterBottons = new JButton(Character.toString(bottonName));
Another way to do it is:
String possibleLetters = "asdaAsadWERWasdas";
for (int i = 0; i <= possibleLetters.length(); i++) {
String buttonName = possibleLetters.substring(i, i + 1);
JButton letterButtons = new JButton(buttonName);
}
Depending on the implementation 1 of the String
class, this might give you marginally better performance.
1 - In older versions of Java, the substring
method would create a String
object that shared its backing array with the original one. By constrast the Character.toString()
method creates a string with its own (newly allocated) backing array. This changes in Java 7. Now the substring
creates a String that does NOT share its backing array. This neatly illustrates why this level of micro-optimization can be a waste of time in the long term.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.