如何在 JTextField 中放入随机文本?
我想在文本字段内显示随机播放的单词。 到目前为止,这是我的随机代码:
public MyTextTwist(String w){
if (w != null){
word = getRandomWord();
txtWord.setText(word);}
GameOver = false;
}
private String getRandomWord(){
ArrayList<Character> chars = new ArrayList<Character>(txtWord.getText().length());
for ( char c : word.toCharArray() ) {
chars.add(c);
}
Collections.shuffle(chars);
char[] shuffled = new char[chars.size()];
for ( int i = 0; i < shuffled.length; i++ ) {
shuffled[i] = chars.get(i);
}String shuffledWord = new String(shuffled);
return shuffledWord;
}
它没有显示。
I want to show the shuffle word inside the Textfield.
so far this is my random code:
public MyTextTwist(String w){
if (w != null){
word = getRandomWord();
txtWord.setText(word);}
GameOver = false;
}
private String getRandomWord(){
ArrayList<Character> chars = new ArrayList<Character>(txtWord.getText().length());
for ( char c : word.toCharArray() ) {
chars.add(c);
}
Collections.shuffle(chars);
char[] shuffled = new char[chars.size()];
for ( int i = 0; i < shuffled.length; i++ ) {
shuffled[i] = chars.get(i);
}String shuffledWord = new String(shuffled);
return shuffledWord;
}
It Doesn't show.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
同样,如果要将文本放回 JTextField,代码必须通过在 JTextField 上调用 setText(...) 来完成此操作,但不能在构造函数中执行此操作,因为调用构造函数时,用户还没有机会在 JTextField 中输入任何文本。相反,您必须在事件响应中调用此方法,也许在已添加到 JButton 的 ActionListener 中:
Again, if you want to put the text back into the JTextField, the code must do this by calling setText(...) on the JTextField, but you can't do this in the constructor since when the constructor has been called, the user hasn't had a chance to enter any text into the JTextField. Instead you must call this method in the response to an event, perhaps in an ActionListener that has been added to a JButton: