How to create a simple 2 by 2 equation solver in JavaFX with GUI

A powerful way of developing stand-alone applications with awesome interfaces is JavaFX, it uses FXML codes to develop application’s interfaces whereas the back-end of an application is developed by Java. The way of developing JavaFX applications is somewhat different than developing Java Swing applications, in the beginning, you will be a little bit confusing, but don’t worry you will understand everything when you are learning some key points.

To develop JavaFX applications on your machine, you need to have an IDE(Integrated Development Environment) installed on your machine, you can download one of the following IDE’s on your machine.

  1. IntelliJ >>>click here to download
  2. Eclipse. >>>click here to download
  3. NetBeans. >>>click here to download

Note: I am using IntelliJ IDE in this example.

After installing an IDE, you need to install and combined the “Scene Builder” software package with your IDE for creating awesome interfaces by drag and drop components in JavaFX.

Now let’s create a simple 2 by 2 equation solver(equations will be solved according to Cramer’s rule) application with interfaces in JavaFX.

Step 1: Just open a new JavaFX project in your IDE (just set your project name as “Equation Solver”),

You will have 3 fmain files created in your source folder of your project,

  1. Main.java
  2. Controller.java
  3. sample.fxml

The Sample.fxml file contains the interface of your application, all the statements that are used to function the Interface is written on the Controller.java class.

Step 2: Open your Sample.fxml file in Scene Builder and create the Interface as shown in the figure below.

or you can paste the source code below in Sample.fxml file in your IDE,

<?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.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.text.Font?>

<GridPane alignment="center" hgap="10" prefHeight="108.0" prefWidth="358.0" vgap="10" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
    <columnConstraints>
        <ColumnConstraints />
        <ColumnConstraints maxWidth="687.0" minWidth="675.0" prefWidth="675.0" />
        <ColumnConstraints maxWidth="19.0" minWidth="7.0" prefWidth="19.0" />
    </columnConstraints>
    <rowConstraints>
        <RowConstraints />
        <RowConstraints />
        <RowConstraints />
    </rowConstraints>
    <children>
        <AnchorPane prefHeight="260.0" prefWidth="684.0" GridPane.columnIndex="1" GridPane.rowIndex="1">
            <children>
                <Label layoutX="217.0" layoutY="14.0" text="2 by 2 Equation Solver" textFill="#e10909">
                    <font>
                        <Font size="22.0" />
                    </font>
                </Label>
                <Label layoutX="210.0" layoutY="40.0" text="Solves a 2 by 2 System Linear Equations" />
                <Label layoutX="164.0" layoutY="56.0" text="All the equations are solved by following Cramer's rule" />
                <AnchorPane layoutX="57.0" layoutY="69.0" prefHeight="242.0" prefWidth="613.0">
                    <children>
                        <Label layoutX="28.0" layoutY="14.0" text="Directions: Enter the coefficiants of 2 linear equations,then click on "Solve"">
                            <font>
                                <Font name="System Bold" size="13.0" />
                            </font>
                        </Label>
                        <Label layoutX="14.0" layoutY="69.0" text="Equation 1:" />
                        <TextField fx:id="eq1_co1" layoutX="102.0" layoutY="64.0" prefHeight="26.0" prefWidth="86.0" />
                        <Label layoutX="188.0" layoutY="69.0" text="x" />
                        <Label layoutX="212.0" layoutY="69.0" text="+" />
                        <TextField fx:id="eq1_co2" layoutX="245.0" layoutY="64.0" prefHeight="26.0" prefWidth="86.0" />
                        <Label layoutX="331.0" layoutY="69.0" text="y" />
                        <Label layoutX="366.0" layoutY="69.0" text="=" />
                        <TextField fx:id="eq1_answer" layoutX="391.0" layoutY="66.0" prefHeight="26.0" prefWidth="157.0" />
                        <Label layoutX="14.0" layoutY="112.0" text="Equation 2:" />
                        <TextField fx:id="eq2_co1" layoutX="102.0" layoutY="107.0" prefHeight="26.0" prefWidth="86.0" />
                        <Label layoutX="188.0" layoutY="112.0" text="x" />
                        <Label layoutX="212.0" layoutY="112.0" text="+" />
                        <TextField fx:id="eq2_co2" layoutX="245.0" layoutY="107.0" prefHeight="26.0" prefWidth="86.0" />
                        <Label layoutX="331.0" layoutY="112.0" text="y" />
                        <Label layoutX="366.0" layoutY="112.0" text="=" />
                        <TextField fx:id="eq2_answer" layoutX="391.0" layoutY="109.0" prefHeight="26.0" prefWidth="157.0" />
                        <Button fx:id="solve_btn" layoutX="14.0" layoutY="158.0" mnemonicParsing="false" onMouseClicked="#solve" style="-fx-cursor: hand;" text="Solve" />
                        <Button fx:id="reset_btn" layoutX="83.0" layoutY="158.0" mnemonicParsing="false" onMouseClicked="#reset" style="-fx-cursor: hand;" text="Reset" />
                        <Label layoutX="260.0" layoutY="163.0" text="X = " />
                        <Label layoutX="260.0" layoutY="196.0" text="Y = " />
                        <Label fx:id="result_x" layoutX="313.0" layoutY="163.0" text="Result" />
                        <Label fx:id="result_y" layoutX="313.0" layoutY="196.0" text="Result" />
                        <Label layoutX="474.0" layoutY="217.0" text="Created by ProramCounter">
                            <font>
                                <Font size="10.0" />
                            </font>
                        </Label>
                    </children>
                </AnchorPane>
            </children>
        </AnchorPane>
    </children>
</GridPane>

In this source code, I have changed, all the component’s name in the Interface as shown in the figure below.

Step 3: we have to create an event that works when the “Solve” and “Reset” buttons are clicked. As I mentioned earlier all the programming parts are done in the Controller class.

Paste the following source code in your Controller class.

package sample;

import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;

public class Controller {


        @FXML
        private TextField eq1_co1;

        @FXML
        private TextField eq1_co2;

        @FXML
        private TextField eq1_answer;

        @FXML
        private TextField eq2_co1;

        @FXML
        private TextField eq2_co2;

        @FXML
        private TextField eq2_answer;

        @FXML
        private Button solve_btn;

        @FXML
        private Button reset_btn;

        @FXML
        private Label result_x;

        @FXML
        private Label result_y;



        public void solve(MouseEvent mouseEvent) {
            System.out.println("Solve");

            String equation_1_co_1 = eq1_co1.getText();
            String equation_1_co_2 = eq1_co2.getText();
            String equation_2_co_1 = eq2_co1.getText();
            String equation_2_co_2 = eq2_co2.getText();

            String answer_for_eq1 = eq1_answer.getText();
            String answer_for_eq2 = eq2_answer.getText();

            try {

                double a = Float.parseFloat(equation_1_co_1);
                double b = Float.parseFloat(equation_1_co_2);
                double c = Float.parseFloat(equation_2_co_1);
                double d = Float.parseFloat(equation_2_co_2);
                double e = Float.parseFloat(answer_for_eq1);
                double f = Float.parseFloat(answer_for_eq2);

                double x = ((e*d) - (b*f)) / ((a*d) - (b*c));
                double y = (a*f - e*c) / (a*d - b*c);

                result_x.setText(""+x);
                result_y.setText(""+y);

                System.out.println(x);
                System.out.println(y);

            } catch (NumberFormatException e) {
                System.out.println("Error occured");

                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("Error");
                alert.setHeaderText("Wrong inputs are detected");
                alert.setContentText("Make sure that you have filled all the blank spaces, and entered values are numbers");

                alert.showAndWait();

            }


        }

        public void reset(MouseEvent mouseEvent) {
            System.out.println("Reset");

            eq1_answer.setText("");
            eq2_answer.setText("");

            eq1_co1.setText("");
            eq1_co2.setText("");
            eq2_co1.setText("");
            eq2_co2.setText("");




            result_x.setText("Result");
            result_y.setText("Result");


        }



}

Just look at what I have done in this source code.

First I instructed the “Solve” button to take inputs from 6 text fields on the interface as Strings, and then I converted those Strings to Floats in order to do the Cramer’s rule, after that, the Cramer’s rule equation will be solved and the result will be printed on the labels in the Interface.

What is Cramer’s rule >>> just click here to see

There are times that the users enter wrong inputs( Characters instead of numbers) or do not fill all the blanks in the interface, at those times the program should generate an Alert to the user. In this program, I have done that part in the catch block.

The Reset button is programmed to empty all the input and output components in the application.

Step 4: Change the source code of your Main class as below.

Source cod

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("2 by 2 Solver");
        primaryStage.setScene(new Scene(root, 683, 331));
        primaryStage.show();
        primaryStage.setResizable(false);
    }


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

In the main class, I have changed the title name of the window and the size of the interface when it runs.

Good, you are done;
You can run your application and test to see whether its work properly or not if it is not, just comment on your problem.

Watch the video below to see how it works,

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.