2013-09-25 35 views
0

我創建了一個javaFx,其中包含一個文本框&,當我單擊該按鈕時,我們在控制檯中收到一條消息,「按鈕被單擊」。現在,我想要讓我在文本框中寫入控制檯的值。這裏是我的代碼..如何在Java類中從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> 
+0

呃...'的System.out.println(gettext的() )'? – millimoose

回答

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()); 
}