In this episode we'll learn how to respond to user interaction.
How to check when a user has click on a button or how to get the text from a TextField for example.
How to check when a user has click on a button or how to get the text from a TextField for example.
- Open in NetBeans the Notes project from last time
- Open the NotesUIController.java, this is the class that will let us respond to user interaction
- First step will be to be able to define new Categories (as you see by default I've put Personal and Work, but we want user to add as many as he like). Use the following code in NotesUIController.java:
package com.turuga.notes;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
public class NotesUIController implements Initializable {
@FXML
private TextField category;
@FXML
private void addCategory(ActionEvent event){
System.out.println("You want to add category:"+category.getText()); }
@Override
public void initialize(URL url, ResourceBundle rb) {
}
}
- The above code will define a TextField variable called category and a method called addCategory. @FXML it is used make this visible into JavaFX.
- Save, then double click on NotesUI.fxml.
- In JavaFX Scene Builder, select the Category TextField (from the bottom left) and look at Inspector window at Property->fx:id and from the drop down list chose category. (that's the private TextField we have defined into file NotesUIController.java).
- Now select the Add button and from Inspector->Code->On Action chose #addCategory
- Save and run the project
- Enter something in the field Category and press Add button. You should see a message in the Java Console with the text you wanted to add.
- You have just successfully respond to user interaction.
In the next episode will learn how to connect to a DB, how to save and retrieve data from the DB...