如何从java类中获取javaFx的值

时间:2013-09-25 13:39:16

标签: xml javafx

我创建了一个javaFx,它有一个按钮&一个文本框,当我点击该按钮时,我们在控制台中收到一条消息“单击按钮”。现在我想获取我在文本框中写入控制台的值。这是我的代码..

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 :(得分:0)

这样做的代码是:

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

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

            }
        });

或者:

@FXML
protected void doSomething() {
   System.out.println(textField.getText());
}