Search code examples
javauser-interfacejavafx-2

Add button to textfield javafx


Simple question I hope. I am looking to add a button to a textfield in java. The textfield will be used to store a file location where a file will be saved / backed up.

Google hasn't been to helpful. Looking for something like this:

 +---------------------------------+
 |  F:\Backup.sql            | ... |
 +---------------------------------+

Assume there is a method to does this.


Solution

  • I think what you are looking for is an HBox where you can add the Textfield and the Button. Hope the following code snipped helps:

    public class BackupUI extends Application{
        @Override
        public void start(Stage primaryStage) throws Exception {
            final HBox hBox = new HBox();
            hBox.setSpacing(5);
    
            final TextField locationTextField = new TextField("F:\\Backup.sql");
            Button saveButton = new Button("Save");
    
            saveButton.setOnAction(event -> save(locationTextField.getText()));
    
            hBox.getChildren().add(locationTextField);
            hBox.getChildren().add(saveButton);
            primaryStage.setScene(new Scene(hBox));
    
            primaryStage.show();
        }
    
        private void save(String fileName) {
            System.out.println(String.format("Backup %s!", fileName));
        }
    }