Search code examples
javaarraysjavafxobservablelist

Trouble sending a char array in one class to an observable list in another in Java


I am new to Java and I am trying to send a string / array generated in one class to another to be used in an observable list. Basically I want the string in one class sent to the other class as a char array to an observable list so the letters can be presented in a tile like format in the GUI.

This is my first class:

public class Phrase {

    String gamePhrase = "Keep moving forwards";
    String guessPhrase = gamePhrase.replaceAll("[a-zA-Z0-9]", "*"); 

    char[] array = guessPhrase.toCharArray();

}

This is my second class where I Am trying to add add the characters to:

private ObservableList<Node> phraseList;

private Phrase p1 = new Phrase();

private void start() {

    phraseList.clear();
    for (p1.toCharArray()) {
        phraseList.add(new LetterBoxes(c));
    }
}


private static class LetterBoxes extends StackPane {
    private Rectangle bg = new Rectangle(40, 60);
    private Text text;

    public LetterBoxes(char x) {
        bg.setFill(x == ' ' ? Color.DARKSEAGREEN : Color.WHITE);
        bg.setStroke(Color.BLUE);

        text = new Text(String.valueOf(x).toUpperCase());
        text.setFont(DEFAULT_FONT);
        text.setVisible(false);

        setAlignment(Pos.CENTER);
        getChildren().addAll(bg, text);
    }
}

I am not sure how to get the array in correctly and am having difficulty moving forward. Any help would be amazing!


Solution

  • for (p1.toCharArray()) {
    

    is wrong for 2 reasons:

    1. The Phrase class does not provide a toCharArray method.
    2. The syntax of the for loop is wrong.

    you probably need a getter for the array in the Phase class and use a enhanced for loop:

    public class Phrase {
    
        public char[] getArray() {
            return array;
        }
    
        ...
    
    }
    
    for (char c : p1.getArray()) {