CodeAddict
CodeAddict

Reputation: 194

Java StringBuilder - appending characters

I have a hangmanframe, welcomeframe, and a mainframe, and I would like to append stars (*) on the mainframe when you win a hangman game

HangmanFrame:

public void win(){
    JOptionPane.showMessageDialog(null, "Congrats! The word was " + GuessWord);
    MainFrame.totalStars.append("*");
    MainFrame.totalLabel.setText(MainFrame.stars);
    setVisible(false);
    MainFrame.hangmanButton.setEnabled(false);
    MainFrame.returnMain();
}

MainFrame:

    public static final StringBuilder totalStars = new StringBuilder();
    public static String stars = totalStars.toString();

    public static void returnMain(){
            totalStars.append("* ");
            totalLabel.setText(stars);
            WelcomeFrame.playButton.doClick();
    }

WelcomeFrame:

    private void playButtonActionPerformed(java.awt.event.ActionEvent evt) {
    String userName = nameText.getText();

    // Open MainFrame
    MainFrame MFrame = new MainFrame();
    MFrame.setVisible(true);
    setVisible(false);
    MainFrame.welcomeLabel.setText("Welcome " + userName + "!");
    MainFrame.totalStars.append("* ");
    MainFrame.totalStarsLabel.setText(MainFrame.stars);
    }

I have a label (totalLabel) that I would like to add stars (*) to. But when the method runs in the HangmanFrame, it goes to the PlayFrame but doesn't add on any stars whatsoever.

Can anyone see what I'm doing wrong?

SOLVED:

changed method name to returnMain()

changed all instances of "stars" with "totalStars.toString()"

Upvotes: 0

Views: 1050

Answers (1)

Juvanis
Juvanis

Reputation: 25950

First, your program will not compile because of public static void return() {..., I think you should know that return is a reserved word in Java.

Second, You make public static String stars = totalStars.toString(); and that is OK, however it doesn't mean that stars will always contain what totalString has. It is just instantaneous.

You should definitely use totalLabel.setText(totalStars.toString());

Upvotes: 1

Related Questions