[英]how to convert char to string
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。
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. 根据String
类的实现1 ,这可能会给您带来稍微更好的性能。
1 - In older versions of Java, the substring
method would create a String
object that shared its backing array with the original one. 1-在Java的旧版本中, substring
方法将创建一个String
对象,该对象与原始数组共享其后备数组。 By constrast the Character.toString()
method creates a string with its own (newly allocated) backing array. 通过比较, Character.toString()
方法创建一个具有其自己的(新分配的)后备数组的字符串。 This changes in Java 7. Now the substring
creates a String that does NOT share its backing array. 这在Java 7中有所更改。现在, substring
创建了一个不共享其后备数组的String。 This neatly illustrates why this level of micro-optimization can be a waste of time in the long term. 这很好地说明了为什么从长远来看,这种微优化水平可能会浪费时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.