How to get value from javaFx from in a java class


Question

I have created a javaFx from that have a button & a textbox and when i click on that button we get a message in the console that "button is clicked" .Now i want to get the value what i write in the textbox to the console. here is my code..

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class CustomControlExample extends Application {
@Override
public void start(Stage stage) throws Exception {
    CustomControl customControl = new CustomControl();
    customControl.setText("Hello!");

    stage.setScene(new Scene(customControl));
    stage.setTitle("Custom Control");
    stage.setWidth(300);
    stage.setHeight(200);
    stage.show();
}

public static void main(String[] args) {
    launch(args);
}
}

import java.io.IOException;

import javafx.beans.property.StringProperty;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;

/**
* Sample custom control hosting a text field and a button.
*/
public class CustomControl extends VBox {

@FXML
private TextField textField;

public CustomControl() {
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("custom_control.fxml"));
    fxmlLoader.setRoot(this);
    fxmlLoader.setController(this);

    try {
        fxmlLoader.load();
    } catch (IOException exception) {
        throw new RuntimeException(exception);
    }
}

public String getText() {
    return textProperty().get();
}

public void setText(String value) {
    textProperty().set(value);
}

public StringProperty textProperty() {
    return textField.textProperty();
}

@FXML
protected void doSomething() {
    System.out.println("The button was clicked!");
}
  }



<?xml version="1.0" encoding="UTF-8"?>


<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

   <fx:root type="javafx.scene.layout.VBox" xmlns:fx="http://javafx.com/fxml">
    <TextField fx:id="textField"/>
     <Button text="Click Me" onAction="#doSomething"/>
  </fx:root>
1
0
9/25/2013 1:39:15 PM

The code to do that would be:

button.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent arg0) {
                System.out.println(textField.getText());

            }
        });

Or:

@FXML
protected void doSomething() {
   System.out.println(textField.getText());
}
0
9/26/2013 11:29:19 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon