Project: JavaFX Calculator

Project: Creating a GUI for Calculator

you should be ready to work on the following assignment: “Create the GUI for a calculator that will look similar to this one”:

fig 7 01

 

Using Scene Builder and a combination of the BorderPane and GridPane layout, create GUI for the calculator that looks as seen in Figure 7.1. Add the TextField to the north region of the BorderPane. Then add a GridPane container to the center area – you’ll add buttons to this container.

Most of the calculators have a display field on top and the buttons just below it. As you can see on Figure 1, the grid with buttons has four columns and six rows. The default GridPane contains two columns and three rows. You’ll need to right-click on the grid and use the menus GridPane | Add Row Above and Add Column After to until you see a 4×6 grid as shown below.

fig 7 18
Figure . The 4×6 GridPane in the center

Note that I set the Padding property to be 10 for all sides of the grid and the Hgap and Vgap to 5 (the gap between the cells).

Save the layout in the file calculator.fxml. Then drop a Button into the top left cell of the grid. Set the Margin property to 5 for each side of this button. This is the distance between the button and cell borders. Drag the button’s border to make it larger. This is what you should see:

fig 7 19
Figure . The grid with one button

If you’re curious how this button looks in the calculator.fxml, open this file in any text editor and note the section <children> that in my case looks like this:

<children>
   <Button mnemonicParsing="false" prefHeight="37.0" prefWidth="132.0" text="Button">
      <GridPane.margin>
         <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
      </GridPane.margin>
   </Button>
</children>

There is no indication of the cell (0,0) because zeros are the default values for GridPane.columnIndex and GridPane.rowIndex properties. Now you need to replicate this button in other cells. You can use multiple Ctrl-C/Ctrl-V commands and then drag/drop the buttons into other cells. See how the content of the calculator.fxml changes as you add more buttons. I find it faster to copy/paste the generated code in the FXML file than using Scene Builder for mass duplication.

Note that in Figure 7.1, the button with coordinates (0,5) spans two columns, and the button with coordinates (3,4) spans two rows. For these buttons you’ll need to enter 2 as the row (or column) span, and select MAX_VALUE as maximum width (or height). This is what you should see by now:

fig 7 20
Figure . Replicated buttons

Change the text of each button to look Figure 7.1, and the layout is done.

Then create a new JavaFX project Calculator in IDEA and replace the generated sample.fxml with calculator.fxml created by Scene Builder. Modify the generated class Main to use calculator.fxml. Rename the package from sample to mycalculator. Set the size of the scene to be large enough to accommodate your design. This is how my class Main looks like:

public class Main extends Application {

  @Override
  public void start(Stage primaryStage) throws Exception{
      Parent root = FXMLLoader.load(getClass().getResource("calculator.fxml"));
      primaryStage.setTitle("My JavaFX Calculator");
      primaryStage.setScene(new Scene(root,650,600));
      primaryStage.show();
  }

  public static void main(String[] args) {
      launch(args);
  }
}

Run the Main program from IDEA to ensure that your calculator looks as expected. Don’t allow the users to resize your calculator by invoking the method setResizable on the stage object.

Then create a CSS file to add some cool styling to the calculator’s buttons. Save the CSS file in your IDEA project and modify the code of the Main class to use your CSS file similarly to how it was done in the section “Styling With CSS” above. Make your calculator look better than mine – it’s not too difficult.

After completing this assignment your buttons won’t work just yet. In the next chapter you’ll learn how to make the buttons (or other components) to react to user actions, so you’ll be able to complete the calculator. In this chapter my goal was to introduce you to basic rules of designing JavaFX GUI with the help of Scene Builder. Watch this YouTube video to see how easy it is to design more complex views with Scene Builder.

Project: Adding Events Handling for Calculator

The goal of this project is to complete the calculator program. If you completed the project from Chapter 7, you can continue working on it. But if you couldn’t complete it on your own, download the version of the calculator GUI that comes with the sample code for this chapter.

  1. Create a Java class CalculatorController in the same IDEA project where the calculator’s GUI is located.
  2. Modify the file calculator.fxml: add the attribute fx:controller="CalculatorController" so it knows the name of the class with the application logic. Use the code of signing.fxml from this chapter as reference.
  3. Create two separate event handler methods in the class CalculatorController. Name the first method digitClickedHandler – it will contain the code to process clicks on the digit buttons. Name the second method operationClickHandler – it will contain the code to process clicks on such buttons as Plus, Minus, et al.
  4. Modify the file calculator.fxml and assign the name of the click handler method for each button using the attribute onAction as we did in the Sign In example.
  5. In each handler method add the code to recognize which button has been clicked. You can do the label of the clicked button by querying the ActionEvent object that will be provided for each event handler method. For example if the variable evt represents the ActionEvent object, the code can look like this:
    Button clickedButton = (Button) evt.getTarget();
    String buttonLabel = clickedButton.getText();
  6. If the user clicks the digit button, get the current value from the calculator’s display field, concatenate the button’s label and assign the new value back to the display field.
  7. You need to declare a variable, say valueOne in the controller to store the current value of the display field when the user clicks on the operation button. For example, if the user clicked on the button with the label +, -, /, or *, it’s a signal that the user finished entering the first number. Store it in the variable valueOne and clear the display field so the user can start entering the second number.
  8. Declare a variable, say operation, to remember the operation that the user wants to perform. For example, if the user clicked on +, store + in the variable operation.
  9. If the user clicks on the button =, get the value from valueOne and from the display field and perform the operation according to the value in operation. Use the switch statement to perform different operations.
  10. After the operation is complete, assign the result to the display field by using the method setText of the TextField component.
  11. Store the calculated result in the variable valueOne so the user can continue performing other operations. For example if the first operation was 2+3, the display shows 5, and the user can click on the buttons * followed by 4 requesting multiplication of 5 by 4.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s