Author Archives: Laxman

Shoot Girl’s Fruits : Archery – non stop action game on Android

shoot girls fruits archery shoot girls fruits archery shoot girls fruits archery shoot girls fruits archery

 

 

 

 

 

 

 

 

 

DOWNLOAD: https://play.google.com/store/apps/details?id=com.marothiatechs.archery

Shoot Girl’s Fruits : Archery is a sequel game for Shoot Girl’s Fruits : Gulel.
Gulel i.e. Slingshot is replaced by Bow and Arrow in this game. So you will use your archery skills instead of stone shooting by a slingshot.

This time you have unlimited arrows for your archer. There are many attacker birds holding canons or mortars. Shoot them too to survive the round.

You need to shoot down fruits or the birds and make sure not to let the birds take away three fruits.

There are different types of arrows available:
Triple Arrows : Three shots in a go.
Row Arrows : Three shots one by one
Strong Arrows : One shot kill arrow.

You can submit your score to compete with your friends for high score.

If you feel like shooting everything in sight then enjoy shooting the birds as well but be careful as you will lose your girl’s fruit if the bird gets hit!
DOWNLOAD: https://play.google.com/store/apps/details?id=com.marothiatechs.archery

484 total views, 10 views today

Purge! An innovative puzzle game.

    

This is a puzzle game with a new and original concept of matching same two numbers or colors in a row of column. You need to cross a line on any two blocks of same number or color. The other block between the two blocks will be eliminated. So the goal is to cut all the cells of the board such that not a single cell is left.

The game is available in three modes:

1) Packages Mode: Many different packages containing hundreds of levels in each of them.
2) Time Trial Mode: In this mode you have to solve the boards as fast as possible. There are two type of games within this mode:
-Timer Mode: Solve as many boards as possible in given time frame.
– Boards Mode: Solve fixed number of boards in minimum time.
You can choose the grid size of your choice in this mode. Grid sizes are available from 3×3 to 9×9.
3) Daily Challenge: Solve an exciting puzzle of challenging difficulty every day and earn some hammers.

Hammers: This is a power in the game which can be used to break any line draw during the gameplay i.e. you can break any line whenever you want using a hammer. Just double tap on the line to use a hammer.

This game is brought to you by the developers of Shoot Girl’s Fruits : Gulel

DOWNLOAD: http://onelink.to/purge

390 total views, 5 views today

Encrypt String in PHP and Decrypt in JAVA Sample Example Tutorial

In this tutorial, We will learn about how to encrypt a string data using RSA algorithm through PHP and decrypt the same using Java project.

We need phpseclib library for encrypting the data. This can be downloaded from :

https://github.com/phpseclib/phpseclib/tree/master/phpseclib

Now lets create php scripts to encrypt a simple string “Hello World!”.

We need two .php files for this :

  1. keypair.php – for generating public key & private key required by RSA Algorithm for encryption.
  2. encrypt.php – for encrypting the string “Hello world!”.

Now copy the below code into keypair.php:

<?php

set_time_limit(0);
if( file_exists('private.key') )
{
    echo base64_encode(file_get_contents('private.key'));
}
else
{
    include('Crypt/RSA.php');

    $rsa = new Crypt_RSA();
    $rsa->setHash('sha1');
    $rsa->setMGFHash('sha1');
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
    $rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
    $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);

    $res = $rsa->createKey(1024);

    $privateKey = $res['privatekey'];
    $publicKey  = $res['publickey'];

    file_put_contents('public.key', $publicKey);
    file_put_contents('private.key', $privateKey);

    echo base64_encode($privateKey);
}

?>

And the code for encrypt.php is as follows:

<?php
    include('Crypt/RSA.php');
    set_time_limit(0);

    $rsa = new Crypt_RSA();
    $rsa->setHash('sha1');
    $rsa->setMGFHash('sha1');
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);

    $rsa->loadKey(file_get_contents('public.key')); // public key

    $plaintext  = 'Hello World!';
    $ciphertext = $rsa->encrypt($plaintext);
    $md5        = md5($ciphertext);
    file_put_contents('md5.txt', $md5);
    file_put_contents('encrypted.txt', base64_encode($ciphertext));

    echo base64_encode($ciphertext);

?>

NOTE: If there is an error on include statement, Simply copy the whole directory structure with files from phpseclib library to resolve: include(‘Crypt/RSA.php’)

Now we are done for the (server side) PHP part of code.

I am using cpanel on a hosting platform and my project structure for php side is as follows:

string encrypt php & java

string encrypt php & java

Now lets work on the Java Part:

We need two libraries for our java project to decrypt the string we encrypt in encrypt.php:

  1. bcprov.jar
  2. sun.misc.BASE64Decoder.jar

Download this zip which contains both these files: libs

Create a new java project in Eclipse (I have used eclipse IDE for this java project).  Now extract the libs.zip and copy the libs folder in root directory of your java project. Add both the jar files to build path of your java project.

 

Now create a new file Main.java with following code:

package testEncryption;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.StringReader;
import java.net.URL;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.Security;

import javax.crypto.Cipher;

import org.bouncycastle.openssl.PEMReader;

import Decoder.BASE64Decoder;


public class Main {

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        try {
            BASE64Decoder decoder   = new BASE64Decoder();
            
            String b64PrivateKey    = getContents("http://www.yourdoamin.com/pathto/keypair.php").trim();
            String b64EncryptedStr  = getContents("http://www.yourdoamin.com/pathto/encrypt.php").trim();
         
            System.out.println("PrivateKey (b64): " + b64PrivateKey);
            System.out.println(" Encrypted (b64): " + b64EncryptedStr);

            byte[] decodedKey           = decoder.decodeBuffer(b64PrivateKey);
            byte[] decodedStr           = decoder.decodeBuffer(b64EncryptedStr);
            PrivateKey privateKey       = strToPrivateKey(new String(decodedKey));

            Cipher cipher               = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);


            byte[] plainText            = cipher.doFinal(decodedStr);

            System.out.println("         Message: " + new String(plainText));
        }
        catch( Exception e )
        {
            System.out.println("           Error: " + e.getMessage());
        }

    }

    public static String getContents(String url)
    {
        try {
            String result = "";
            String line;
            URL u = new URL(url);
            DataInputStream theHTML = new DataInputStream(u.openStream());
            while ((line = theHTML.readLine()) != null)
                result = result + "\n" + line;

            return result;
        }
        catch(Exception e){}

        return "";
    }

    public static PrivateKey strToPrivateKey(String s)
    {
        try {
            BufferedReader br   = new BufferedReader( new StringReader(s) );
            PEMReader pr        = new PEMReader(br);
            KeyPair kp          = (KeyPair)pr.readObject();
            pr.close();
            return kp.getPrivate();
        }
        catch( Exception e )
        {

        }

        return null;
    }
}

NOTE: Please provide the URLs for the PHP files we just created in this tutorial in Main.java file.

My project structure for java project:
rsa decryption java

Now the Main.java file as Java Application and you will see that
hello world!
is printed on the console!

We have successfully encrypted and decrypted the string between PHP and JAVA!

1,286 total views, 16 views today

Stone Pillar – A game about stacking stones

You will love this game if you have ever played with mountain stones to create balanced structures.
Stack stones wherever you want by simply touching the screen. Its just your creativity that will decide the structure of your building.
– Pile Up the blocks as high as you can.
– Complete Levels in classic mode.
– Arrange stones to create highest tower of balanced wall.
– Simple & Beautiful graphics designed
– Compete for the best score in the world.
– Share beautiful buildings constructed..

DOWNLOAD FROM GOOGLE PLAY STORE

 

1,372 total views, 8 views today

How to use Jasper Reports in JavaFX 8 – Sample Example Tutorial

Jasper Reports are used for showing information that need to be printed or saved as document file.

Use Cases:

– For printing Reciepts
– Bill/ Invoice
– Detailed Reports
– and so on..

If you have already developed some Java application/ Software using JavaFx and now need to print some data from the software, then this is the tutorial for you.

Jasper Reports are designed in the form of .jrxml files similar to .fxml files of javaFX.
We need to access these .jrxml files in java class and pass the data to be filled in the Jasper report using Java Objects(List) or through an SQL query.

Steps required to achieve this:

1) Install Jaspersoft Studio for creating .jrxml file using drag and drop.
2) Get Jasper Reports Library .jar files to be added in libs folder of your JavaFX project.
4) Design .jrxml file using JasperSoft Studio.
3) Write Java code to show .jrxml file as Report.

Install Jaspersoft Studio

You can either download Jaspersoft studio plugin for eclipse OR download Standalone Jasper soft Studio. We just need the .jrxml report files designed using either of the above.

1) Eclipse Plugin: Search JasperSoft in Eclipse MarketPlace and install the latest release.
jaspersoft studio javafx download plugin

2) Standalone JasperSoft Studio: Download


Get Jasper Reports Library

We need jasper library for java project. To get the library files. Download the Jasper Reports Library from here.

jasper Reports Library for Java download

Download the “jasperreports-6.3.1-project.zip” in the above screenshot.

After extracting the zip file you will get the project folder in which “dist” folder is of our concern.
jasper dist folder
There are 3 .jar files in this dist folder. Add all the three files to the libs folder of your javaFX project.
But these 3 jar files are not enough. There are many other dependencies require by Jasper Reports which should be again added to the libs folder of your project.

The Jasper Reports Project uses Apache Ant, Apache Ivy – as the dependency Manager. We need to get the Apache Ant/Ivy for getting the remaing .jar files.

We have to Download Apache Ant and run the commands on Jasper Reports Project’s root directory using Terminal/Command Prompt.

Download Apache Ivy, Apache Ant from here:
Ant
(You can alway get the latest releases by searching on Google)

Extract the downloaded .zip file and copy the folder ant anywhere near the Jasper Reports Project folder.
Directory structure of ant and jasper project

Now run the following command in the root directory of the Jasper Reports project:

java -jar ../ant/ant-launcher.jar retrievelibs

Look at the screenshot showing how I ran the above command:

terminal showing ant retrieving Jasper reports library for java

The required dependency .jar files will be downloaded into the dist/libs folder of the JasperReports project.
Copy all the .jar files from this lib folder to the libs folder of your java project.

jasper dependency jar files

NOTE: Add all the jar files to the Build Path of your Java project.
Here is the list of all the jar files that will be added to the libs folder of your JavaFX Project:

  1. ant-1.7.1.jar
  2. antlr-2.7.5.jar
  3. asm-all-4.0.jar
  4. barbecue-1.5-beta1.jar
  5. barcode4j-2.1.jar
  6. batik-anim-1.8.jar
  7. batik-awt-util-1.8.jar
  8. batik-bridge-1.8.jar
  9. batik-css-1.8.jar
  10. batik-dom-1.8.jar
  11. batik-gvt-1.8.jar
  12. batik-svg-dom-1.8.jar
  13. batik-svggen-1.8.jar
  14. batik-util-1.8.jar
  15. bsh-2.0b4.jar
  16. castor-core-1.3.3.jar
  17. castor-xml-1.3.3.jar
  18. commons-beanutils-1.9.0.jar
  19. commons-collections-3.2.2.jar
  20. commons-digester-2.1.jar
  21. commons-javaflow-20160505.jar
  22. commons-lang-2.6.jar
  23. commons-logging-1.1.1.jar
  24. core-3.2.1.jar
  25. ecj-4.3.1.jar
  26. groovy-all-2.4.5.jar
  27. hibernate-core-3.3.2.GA.jar
  28. httpclient-4.3.4.jar
  29. httpcore-4.3.2.jar
  30. icu4j-57.1.jar
  31. itext-2.1.7.js5.jar
  32. jackson-annotations-2.1.4.jar
  33. jackson-core-2.1.4.jar
  34. jackson-databind-2.1.4.jar
  35. jasperreports-6.3.1.jar
  36. jasperreports-fonts-6.3.1.jar
  37. jasperreports-javaflow-6.3.1.jar
  38. jaxen-1.1.1.jar
  39. jcommon-1.0.23.jar
  40. jfreechart-1.0.19.jar
  41. jxl-2.6.10.jar
  42. lucene-analyzers-common-4.5.1.jar
  43. lucene-core-4.5.1.jar
  44. lucene-queryparser-4.5.1.jar
  45. mondrian-3.1.1.12687.jar
  46. olap4j-0.9.7.309-JS-3.jar
  47. persistence-api-1.0.jar
  48. poi-3.10.1.jar
  49. poi-ooxml-3.10.1.jar
  50. rhino-1.7.6.jar
  51. servlet-api-2.4.jar
  52. spring-beans-2.5.jar
  53. spring-core-2.5.jar
  54. velocity-1.7.jar
  55. xalan-2.7.2.jar
  56. xml-apis-ext-1.3.04.jar
  57. xmpcore-5.1.1.jar

Design .jrxml file using JasperSoft Studio.

Open Jasper Studio and create a new Jasper Report as shown below:

Creating new Jasper Report

Now select Blank A4 as the Report Template as shown below:

Jasper Report Template

Choose the name and directory for the jrxml file and at the screen asking for Data Source, select “New Data Adapter – Empty Rows” from the drop down as shown below:

Selecting data source for jasper report

Click Next->Finish to create the jrxml file. Look at the screenshot below:

Jasper new reports

You can download the sample .jrxml file here: Blank_A4.jrxml
Create a folder named data in your java project and Copy the created .jrxml file there.
Now create a java file named PrintReport.java as follows:

package com.marothiatechs.reports;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JFrame;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.swing.JRViewer;

public class PrintReport extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void showReport() throws JRException, ClassNotFoundException, SQLException {

		String reportSrcFile = "data/Blank_A4.jrxml";

		// First, compile jrxml file.
		JasperReport jasperReport = JasperCompileManager.compileReport(reportSrcFile);
		// Fields for report
		HashMap<String, Object> parameters = new HashMap<String, Object>();

		parameters.put("company", "MAROTHIA TECHS");
		parameters.put("receipt_no", "RE101".toString());
		parameters.put("name", "Khushboo");
		parameters.put("amount", "10000");
		parameters.put("receipt_for", "EMI Payment");
		parameters.put("date", "20-12-2016");
		parameters.put("contact", "98763178".toString());

		ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
		list.add(parameters);

		JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(list);
		JasperPrint print = JasperFillManager.fillReport(jasperReport, null, beanColDataSource);
		JRViewer viewer = new JRViewer(print);
		viewer.setOpaque(true);
		viewer.setVisible(true);
		this.add(viewer);
		this.setSize(700, 500);
		this.setVisible(true);
		System.out.print("Done!");

	}

}

Now call the source code for the Main.Java is as follows:

package com.marothiatechs.finance;

import java.sql.SQLException;

import com.marothiatechs.reports.PrintReport;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import net.sf.jasperreports.engine.JRException;

public class Main extends Application {

	Stage window;
	Scene scene;
	Button button;

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

	@Override
	public void start(Stage primaryStage) throws Exception {
		window = primaryStage;
		window.setTitle("Jasper Report Tutorial");
		button = new Button("Show Receipt");
		button.setOnAction(e -> {
			try {
				// --- Show Jasper Report on click-----
				new PrintReport().showReport();
			} catch (ClassNotFoundException | JRException | SQLException e1) {
				e1.printStackTrace();
			}
		});

		VBox layout = new VBox(10);
		layout.setPadding(new Insets(20, 20, 20, 20));
		layout.getChildren().addAll(button);
		scene = new Scene(layout, 300, 250);
		window.setScene(scene);
		window.show();
	}

}

Now Run the Main.java file as Java Application:
Jasper Report running in JavaFX JFrame

5,421 total views, 32 views today

[Solved] Unable to boot, Grub Rescue Error: No such Partition Solution Tutorial

If you have installed more than one Operating System in your PC. For example, you have Windows 7 & Ubuntu installed and suddenly you are unable to boot to any of the OS. If the error similar to given below appears:

error-no-such-partition-1
That means you have a problem with your bootloader.

A very simple solution for this would be to boot into the live CD/USB and run Boot Repair

Boot Repair PPA

Boot into Live CD/USB.
Type the following in terminal(one line at a time)

sudo add-apt-repository ppa:yannubuntu/boot-repair  
sudo apt-get update  
sudo apt-get install -y boot-repair

Run Boot Repair
Type in terminal

sudo boot-repair

or

type in Unity dash
Boot Repair
boot-repair

Click the Recommended repair button
enter image description here
After the process is finished close everything.
This should solve your problem.

644 total views, 4 views today

How to make Numeric | Decimal TextField in JavaFX Example Tutorial

JavaFx provides various default layout controllers for taking inputs from the user. One such controller is TextField. The problem with this controller is that it accepts every input provided by the user.

If we need a TextField which accepts floating point numbers or double values, then we need to modify the existing TextField. Textfields with numeric values are needed for making apps/softwares that require numeric calculations.

Numeric TextField:

step-1) Create a normal TextField in JavaFx App.
step-2) Add a listener to the textfield that calls when text is changed in the textfield as shown below.

textField.textProperty().addListener(new ChangeListener<String>() {
			@Override
			public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
				if (!newValue.matches("\\d{0,7}([\\.]\\d{0,4})?")) {
					vehiclePrice_TextField.setText(oldValue);
				}
			}
		});

Thats it! :-p

“\\d{0,7}([\\.]\\d{0,4})?” <- Its the regular expression for numeric values that can be accepted. Explanation for the above regular expression: Screen Shot 2016-12-09 at 10.50.41 AM

You can change the regular expression for changing the length of the numeric value to be accepted.
The values that can be accepted by the Numeric Textfield we just created are shown below.
Screen Shot 2016-12-09 at 10.22.47 AM

Thank You!

1,550 total views, 13 views today

Tips: Remove all comments from the java files in Eclipse IDE

1) Open the java file in which comments are to be removed.
2) Press Ctrl+F if you are using windows, Cmd+F in Mac OS.
3) Select Regular Expressions in the Find Menu.
4) Replace the below two expressions with empty string:

i) (//[^\n]*)
ii) (?s)/\*.*?\*/

5) This action will remove all the comments -> Single Line as well as multiple line comments from the java file.

836 total views, 6 views today

Build Desktop application software using Java Tutorial | Sample Examples -Part 3

In the previous part, we saw how to create AlertBox, switching scenes etc for the desktop application using JavaFX. Lets go ahead with the following sections today :

  • Communicating Between Windows
  • GridPane
  • Extract And Validate Input
  • CheckBoxes
  • ChoiceBox DropDown List

Communicating Between Window

Let look at how to make java application to communicate between two windows. For example : Asking user to enter some name using prompt window.

Create a new class named ConfirmBox.java and replace the content with:


import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

public class ConfirmBox {

    //Create variable
    static boolean answer;

    public static boolean display(String title, String message) {
        Stage window = new Stage();
        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle(title);
        window.setMinWidth(250);
        Label label = new Label();
        label.setText(message);

        //Create two buttons
        Button yesButton = new Button("Yes");
        Button noButton = new Button("No");

        //Clicking will set answer and close window
        yesButton.setOnAction(e -> {
            answer = true;
            window.close();
        });
        noButton.setOnAction(e -> {
            answer = false;
            window.close();
        });

        VBox layout = new VBox(10);

        //Add buttons
        layout.getChildren().addAll(label, yesButton, noButton);
        layout.setAlignment(Pos.CENTER);
        Scene scene = new Scene(layout);
        window.setScene(scene);
        window.showAndWait();

        //Make sure to return answer
        return answer;
    }

}

This class contains the code for creating a window within the app which will prompt user for some action.
Now lets use the above class in our application
Replace the content of Main.java with the following:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {

    Stage window;
    Button button;

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

    @Override
    public void start(Stage primaryStage) {
        window = primaryStage;
        window.setTitle("JavaFX - Tutorials Face");
        button = new Button("Click Me");

        button.setOnAction(e -> {
            boolean result = ConfirmBox.display("Title of Window", "Are you sure you want to send that pic?");
            System.out.println(result);
        });

        StackPane layout = new StackPane();
        layout.getChildren().add(button);
        Scene scene = new Scene(layout, 300, 250);
        window.setScene(scene);
        window.show();
    }

}

We have called the static method of display() ConfirmBox.java in the above class. I am explaining in detail as the code is self explanatory.

COnfirmBox JavaFX

GridPane

GridPane is a layout similar to StackPane.
GridPane lays out its children within a flexible grid of rows and columns. If a border and/or padding is set, then its content will be layed out within those insets.
A child may be placed anywhere within the grid and may span multiple rows/columns. Children may freely overlap within rows/columns and their stacking order will be defined by the order of the gridpane’s children list.

Replace the Main.java with the following:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class Main extends Application {

    Stage window;

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setTitle("TutorialsFace - JavaFX");

        //GridPane with 10px padding around edge
        GridPane grid = new GridPane();
        grid.setPadding(new Insets(10, 10, 10, 10));
        grid.setVgap(8);
        grid.setHgap(10);

        //Name Label - constrains use (child, column, row)
        Label nameLabel = new Label("Username:");
        GridPane.setConstraints(nameLabel, 0, 0);

        //Name Input
        TextField nameInput = new TextField("Bucky");
        GridPane.setConstraints(nameInput, 1, 0);

        //Password Label
        Label passLabel = new Label("Password:");
        GridPane.setConstraints(passLabel, 0, 1);

        //Password Input
        TextField passInput = new TextField();
        passInput.setPromptText("password");
        GridPane.setConstraints(passInput, 1, 1);

        //Login
        Button loginButton = new Button("Log In");
        GridPane.setConstraints(loginButton, 1, 2);

        //Add everything to grid
        grid.getChildren().addAll(nameLabel, nameInput, passLabel, passInput, loginButton);

        Scene scene = new Scene(grid, 300, 200);
        window.setScene(scene);
        window.show();
    }
}

Gridpane Javafx

Extract And Validate Input

In the above section we saw how to take input from users using a good looking layout. Now let take that input and apply validation checks.

Replace Main.java with:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    Stage window;
    Scene scene;
    Button button;

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setTitle("TutorialsFace");

        //Form
        TextField ageInput = new TextField();

        button = new Button("Click me");
        button.setOnAction( e -> isInt(ageInput, ageInput.getText()) );

        //Layout
        VBox layout = new VBox(10);
        layout.setPadding(new Insets(20, 20, 20, 20));
        layout.getChildren().addAll(ageInput, button);

        scene = new Scene(layout, 300, 250);
        window.setScene(scene);
        window.show();
    }

    //Validate age
    private boolean isInt(TextField input, String message){
        try{
            int age = Integer.parseInt(input.getText());
            System.out.println("User is: " + age);
            return true;
        }catch(NumberFormatException e){
            System.out.println("Error: " + message + " is not a number");
            return false;
        }
    }
}

In the above code we have made a very basic validation test of whether a given input is number of not.

CheckBoxes

Let integrate CheckBoxes in the application. Although checkboxes look similar to radio buttons, they cannot be combined into toggle groups to enable the selection of many options at one time. See the Radio Button and Toggle Button chapters for more information.

Replace Main.Java with:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    Stage window;
    Scene scene;
    Button button;

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setTitle("Bucky's Meat Subs");

        //Checkboxes
        CheckBox box1 = new CheckBox();
        CheckBox box2 = new CheckBox("Tuna");
        box2.setSelected(true);

        //Button
        button = new Button("Order Now!");
        button.setOnAction(e -> handleOptions(box1, box2));

        //Layout
        VBox layout = new VBox(10);
        layout.setPadding(new Insets(20, 20, 20, 20));
        layout.getChildren().addAll(box1, box2, button);

        scene = new Scene(layout, 300, 250);
        window.setScene(scene);
        window.show();
    }

    //Handle checkbox options
    private void handleOptions(CheckBox box1, CheckBox box2){
        String message = "Users order:\n";

        if(box1.isSelected())
            message += "Bacon\n";

        if(box2.isSelected())
            message += "Tuna\n";

        System.out.println(message);
    }
}

JavaFx Checkbox

ChoiceBox DropDown List

Choice Boxes are the UI controls that provide support for quickly selecting between a few options.

Replace Main.Java with the following:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    Stage window;
    Scene scene;
    Button button;

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setTitle("ChoiceBox Demo");
        button = new Button("Click me");

        ChoiceBox<String> choiceBox = new ChoiceBox<>();

        //getItems returns the ObservableList object which you can add items to
        choiceBox.getItems().add("Apples");
        choiceBox.getItems().add("Bananas");
        choiceBox.getItems().addAll("Bacon", "Ham", "Meatballs");

        //Set a default value
        choiceBox.setValue("Apples");

        button.setOnAction(e -> getChoice(choiceBox));

        VBox layout = new VBox(10);
        layout.setPadding(new Insets(20, 20, 20, 20));
        layout.getChildren().addAll(choiceBox, button);

        scene = new Scene(layout, 300, 250);
        window.setScene(scene);
        window.show();
    }

    //To get the value of the selected item
    private void getChoice(ChoiceBox<String> choiceBox){
        String food = choiceBox.getValue();
        System.out.println(food);
    }


}

Choce Box JavaFX

Look at the screenshot above. It shows how the choice boxes can be used for adding Drop Down lists.

We will see remaining sections in next part.

1,086 total views, 6 views today