我已经创建了一个 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>