JavaFX Button Example

Let’s say that you want to display multiple buttons and have different actions take place because of them. Buttons in JavaFX are just as important as in other UI toolkits. Here is a tutorial giving an example of two JavaFX buttons changing the text of a JavaFX TextField.

If you are brand new to JavaFX, be sure to go through the JavaFX tutorial I wrote a while back. This tutorial assumes you are using Eclipse.

Create a JavaFX Project

The first step to creating our example is creating a JavaFX Project to work in. You can create your JavaFX Project from the menu by selecting the following.

File -> New -> Other …

Then select JavaFX Project┬áthen click Next>. Give your project a name, like ‘two_buttons’ and click Finish.

Create a Java class called ButtonsController in the same package as your Main class. Not too surprisingly, this will be your JavaFX controller for this little Button example.

Create a FXML file in the same package and call it ‘ButtonsPane.fxml’. You will find the template for it in File -> New -> Other …┬ájust as the JavaFX Project was there.

Configuring the JavaFX Scene

Open the FXML file, ButtonsPane.fxml, with SceneBuilder. The default root when your create your FXML file is AnchorPane. You will find your AnchorPane all by itself in the Hierarchy on the left hand side.

Select your AnchorPane. Open up the layout on the right hand side of SceneBuilder to see the Sizes configured for the AnchorPane. The default ones stink. Change Pref Width and Pref Height to a real number like 600 and 400.

Now you can actually see the AnchorPane in the central SceneBuilder window.

Drag a couple of Buttons and a TextField from the right hand Controller and place them in the AnchorPane. Double click on the each button and change the text on one Button to read, “Hello”, and on the other Button to read, “Bye Bye”

Select the Bye Bye Button and look in the Code section on the right. Change fx:id to read “byeBtn” and the On Action field to read, “sayGoodBye”. Do the same with the Hello Button, except make the values “helloBtn” in the fx:id field and “sayHello” in the On Action field.

Now for the TextField, select the TextField and set the fx:id to “sayItTF” in its Code area on the right.

Don’t forget to set your controller for the FXML! This is sooo easy to forget, but nothing in your JavaFX project will work if you forget to hook up your controller.

On the left hand side of the SceneBuilder, select Controller and set the value in the Controller class field to “application.ButtonsController”.

Save the work you have completed in SceneBuilder. It saves automatically to the ButtonsPane.fxml you opened from your Eclipse project. If you open up your FXML file after saving, it will look something like the following.

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane 
  prefHeight="400.0" 
  prefWidth="600.0" 
  xmlns="http://javafx.com/javafx/8.0.40" 
  xmlns:fx="http://javafx.com/fxml/1" 
  fx:controller="application.ButtonsController">
   <children>
      <Button 
        fx:id="helloBtn" 
        layoutX="200.0" 
        layoutY="279.0" 
        mnemonicParsing="false" 
        onAction="#sayHello" 
        text="Hello" />
      <Button 
        fx:id="byeBtn" 
        layoutX="349.0" 
        layoutY="279.0" 
        mnemonicParsing="false" 
        onAction="#sayGoodBye" 
        text="Bye Bye" />
      <TextField 
        fx:id="sayItTF" 
        layoutX="226.0" 
        layoutY="141.0" />
   </children>
</AnchorPane>

Grab a skeleton copy of the your controller code by going to View -> Show Sample Controller Skeleton. Remember to select the Comments checkbox, but not the Full checkbox.

Controlling Your JavaFX Button Behavior

The controller will once again just do some basic work. We’ll look at doing more complex work with your controller in the future.

Set your sayGoodBye() method to change the text in the TextField to “Good-bye!”, and the sayHello() method to set your text to “Hello there!”.

Your controller code will look similar to the following.

/**
 * Sample Skeleton for 'ButtonsPane.fxml' Controller Class
 */

package application;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;

public class ButtonsController {

    @FXML // fx:id="helloBtn"
    private Button helloBtn;

    @FXML // fx:id="byeBtn"
    private Button byeBtn;

    @FXML // fx:id="sayItTF"
    private TextField sayItTF;

    @FXML
    void sayGoodBye(ActionEvent event) {
      sayItTF.setText("Good-bye!");
    }

    @FXML
    void sayHello(ActionEvent event) {
      sayItTF.setText("Hello!");
    }

}

See, there really isn’t that much to it.

Main JavaFX Class

Finally, let’s set up the Main class for the JavaFX example and run it. The code for the Main class looks very similar to the code from the Hello World tutorial. You’ll find that happens a lot.

Here is the last bit of code.

package application;
	
import java.io.IOException;
import java.net.URL;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;


public class Main extends Application{
	@Override
	public void start(Stage primaryStage) throws IOException {
		URL url = getClass().getResource("ButtonsPane.fxml");
		AnchorPane pane = FXMLLoader.load( url );
		Scene scene = new Scene( pane );
		
		primaryStage.setScene( scene );
		primaryStage.setTitle( "Hello / Good-bye" );
		primaryStage.show();
	}
	
	public static void main(String[] args) {
		launch(args);
	}
}

And there you have it, a JavaFX app with two Buttons manipulating one TextField.