我编写了一个程序,当按下按钮一次时,将一个随机单词及其定义打印到文本字段。我想让它在重复按下按钮时打印另一个随机字和定义。有任何想法吗? 我是编码的新手,所以请考虑到这一点。
这是我到目前为止所做的:
<div class="checkbox">
<input id="check1" type="checkbox" name="check" />
<label for="check1"><span class="chk-text">Checklist One<span></label>
<br>
<input id="check2" type="checkbox" name="check" checked>
<label for="check2"><span class="chk-text">Checklist two<span></label>
<br>
<input id="check3" type="checkbox" name="check">
<label for="check3"><span class="chk-text">Checklist three<span></label>
</div> <!-- END OF CHECKBOX -->
<button class="add-item" type="button">Add</button>
</div> <!-- END OF ADD-ITEM -->
<div class="checkbox">
<input id="check1" type="checkbox" name="check" />
<label for="check1"><span class="chk-text">Checklist One<span></label>
<br>
<input id="check2" type="checkbox" name="check" checked>
<label for="check2"><span class="chk-text">Checklist two<span></label>
<br>
<input id="check3" type="checkbox" name="check">
<label for="check3"><span class="chk-text">Checklist three<span></label>
</div> <!-- END OF CHECKBOX -->
<button class="add-item" type="button">Add</button>
</div> <!-- END OF ADD-ITEM -->
}
答案 0 :(得分:0)
您正在选择构造函数中的随机单词和定义。
单击鼠标(在actionPerformed
方法内)时,必须更改此选项以选择随机单词和定义。
试试这个:
public RandomWord(){
super("Cool Words -1.5");
setLayout(new FlowLayout());
wordField = new JTextField("Petrichor",20);
add(wordField);
defField = new JTextField("The smell of earth after rain",20);
add(defField);
nextButton = new JButton("Next");
add(nextButton);
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// this method is executed when you clicked;
// The random word and definition must be choose at this moment.
int idx = new Random().nextInt(words.length);
wordField.setText(words[idx];);
defField.setText(def[idx]);
}
});
}
答案 1 :(得分:0)
尝试删除字符串中的final关键字。 Final表示在声明后不能更改String值:
String randomWord = words[idx];
String randomDef = def[idx];