[英]java dynamic display JLabel
I have a button. 我有一个按钮。 If I click this button, a popup appears. 如果单击此按钮,将显示一个弹出窗口。 The popup asking me to write a word. 弹出窗口要求我写一个字。 if I write a word 6 letter, 6 jlabels appear, but if I enter another word shorter, the JLabels do not disappear 如果我写一个单词6个字母,则会出现6个jlabel,但是如果我输入的单词较短,则JLabel不会消失
I want my JLabels may decrease according to a shorter word, but i don't know :( 我希望我的JLabels可能会根据一个简短的词减少,但我不知道:(
thx for your great help ! 感谢您的大力帮助!
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//BUTTON 1 WORD
Controller c = new Controller();
try {
final JFrame popup = new JFrame();
//display popup
word = JOptionPane.showInputDialog(popup, "Enter one word", null);
//control the length of the word
c.controleW(word);
//display jlabel lenght of word
keyNumber.setText(String.valueOf(word.length()));
//JLabels displays depending on the word length
int pixels = 50;
for (int i = 0; i < word.length(); i++) {
label = new JLabel("_");
label.setBounds(pixels, 200, 30, 30);
add(label);
label.repaint();
pixels += 20;
}
} catch (Exception e) {
System.out.println(e);
}
}
And my class to control the length of the word 和我的班来控制单词的长度
public String controleW(String word) {
boolean flag = false;
final JFrame popup = new JFrame();
while (flag == false) {
if (word.length() <= 3) {
word = JOptionPane.showInputDialog(popup, "Enter one word", null);
} else {
flag = true;
}
};
return null;
}
You are always adding labels in your method, never removing any, thus running the code twice will indeed add labels twice. 您总是在方法中添加标签,而从不删除任何标签,因此,运行两次代码确实会两次添加标签。 To fix it, you can simply add a removeAll();
要修复它,您只需添加removeAll();
in jButton1ActionPerformed before you add any labels. 在jButton1ActionPerformed中添加任何标签之前。 This makes sure that any previously added components will be removed. 这样可以确保删除所有以前添加的组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.