我正在设计一个联系人列表应用程序,到目前为止,我仍然坚持一些非常简单的事情。目前出于测试目的,我想要它,以便当我点击“saveButton”按钮时,它会将从“nameField”TextField输入的文本打印到控制台中。这是我的代码:
public class Controller {
// main_activity window objects
@FXML private Button btnAdd;
@FXML private Button btnSearch;
@FXML private TableColumn nameCol;
@FXML private TableColumn phoneCol;
@FXML private TableColumn emailCol;
// add_contact window objects
@FXML private TextField phoneField;
@FXML private TextField nameField;
@FXML private TextField emailField;
@FXML private Button saveButton;
@FXML
public void addContact(ActionEvent actionEvent) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("add_contact.fxml"));
Stage stage = new Stage();
stage.setTitle("Add Contact");
stage.setScene(new Scene(root, 385, 285));
stage.setResizable(false);
stage.show();
}
@FXML
public void saveContact(ActionEvent actionEvent) {
System.out.println(nameField.getText());
}
}
FXML文件
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="300.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controller">
<children>
<Label layoutX="145.0" layoutY="22.0" text="Add Contact">
<font>
<Font size="20.0" />
</font>
</Label>
<TextField id="nameField" fx:id="nameField" layoutX="14.0" layoutY="77.0" onAction="#saveContact" prefHeight="31.0" prefWidth="373.0" />
<TextField id="phoneField" fx:id="phoneField" layoutX="14.0" layoutY="143.0" prefHeight="31.0" prefWidth="373.0" />
<TextField id="emailField" fx:id="emailField" layoutX="14.0" layoutY="205.0" prefHeight="31.0" prefWidth="373.0" />
<Button id="saveButton" fx:id="saveButton" layoutX="327.0" layoutY="255.0" mnemonicParsing="false" prefHeight="31.0" prefWidth="59.0" text="Save" />
<Label layoutX="14.0" layoutY="52.0" text="Name" />
<Label layoutX="14.0" layoutY="118.0" text="Phone" />
<Label layoutX="16.0" layoutY="188.0" text="Email" />
</children>
</AnchorPane>
非常感谢任何帮助!
答案 0 :(得分:2)
您的按钮在FXML中没有onAction属性,指定在按下按钮后应该调用哪个方法。