David Frick
David Frick

Reputation: 776

JavaFX - TextArea where multiple buttons drop Text

I have a TabPane with an expandable number of buttons (around 20+). I want an area to its left to concatenate previous text with the new text that each button holds.

So at the start, the TextArea (maybe not the best to use) is blank. Then you press Tab Foo then one of its respective buttons Bar. The textarea will be populated with Bar - $10000000000000

I am using a StringBuilder. Do I need to have each button add text to the StringBuilder then set the TextArea to show that text? I feel that results in really redundant code for each button. However, I think this is the only way because the TextArea will only be able to get the text when that specific button is pressed....

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextArea;

/**
 * FXML Controller class
 *
 * @author David
 */
public class MainMenuController implements Initializable {

    private StringBuilder fieldContent;

    @FXML TextArea txtReceipt;

    @FXML
    void btnExample(ActionEvent event) {
        fieldContent.append(btnExample.getText());
        txtReceipt.setText(fieldContent.toString());
    }

    void btnExample2(ActionEvent event) {
        fieldContent.append(btnExample.getText());;
        txtReceipt.setText(fieldContent.toString());
    }

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        fieldContent = new StringBuilder("");
    }    

}

Upvotes: 0

Views: 1020

Answers (1)

Eric
Eric

Reputation: 601

Repeating 20+ blocks of the same code is certainly a violation of the DRY principle! Instead of using a unique handler function for each button, go back to your FXML and have them all point to a single handler. You can write a generic handler like this:

@FXML
public void buttonPressHandler(ActionEvent event) {
    Button b = (Button) event.getSource();
    fieldContent.append(b.getText());
    txtReceipt.setText(fieldContent.toString());
}

Edit:

As Fabian mentioned in comments of the original question, TextArea has an appendText method already built in so you can remove the StringBuilder and alter the handler like so:

@FXML
public void buttonPressHandler(ActionEvent event) {
    Button b = (Button) event.getSource();
    txtReceipt.appendText(b.getText());
}

Upvotes: 3

Related Questions