Reputation: 41
I have just started learning java fx and I am trying to get user input from two text field. Once they click the button this will be displayed on a console. However, I am keep getting an error and cannot figure out why. I have assigned the 'handle' function using Scenebuilder, the error is pointing at the method.
Main Class:
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller:
package sample;
import javafx.event.ActionEvent;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
public class Controller {
public TextField userField;
public TextField passField;
public Button logButton;
public void handle(ActionEvent event) {
String username = userField.getText();
String passw = passField.getText();
System.out.printf("Logged in as %s %s", username, passw);
}
}
Upvotes: 1
Views: 9268
Reputation: 2227
As you are using Scene Builder, you should use the sample controller skeleton: Under View, select Use Sample Controller Skeleton. Also, specify the "On Action" for the text field. Scene Builder will dot the i's and cross the t's for you.
Upvotes: 0
Reputation: 678
although you didn't show the error, but i think it's because you didn't annotate the fields userField
and passwordField
with @FXML
annotation
by this annotation you tie the fields in the controller with fields in the fxml
so to solve this problem let's do the following simple steps
public class Controller implements Initializable{
@FXML
private TextField userField;
@FXML
private TextField passField;
@FXML
private Button logButton;
private void handle(ActionEvent event)
{
System.out.println(userField.getText());
}
@Override
public void initialize(URL url, ResourceBundle rb)
{
logButton.setOnAction(this::handle);
}}
and in the scene builder follow this image
try this,and if you still have problems just let a comment (:
Upvotes: 2