Frage

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

I want my JLabels may decrease according to a shorter word, but i don't know :(

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;
}
War es hilfreich?

Lösung

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(); in jButton1ActionPerformed before you add any labels. This makes sure that any previously added components will be removed.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top