Author Archives: Laxman

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

23,219 total views, 9 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.

4,114 total views, 5 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!

22,435 total views, 8 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.

9,981 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.

4,940 total views, 3 views today

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

In the previous part, we saw a very basic template for the desktop application using JavaFX. Lets go ahead with the following sections today in this part :

  • Handle User Events
  • Anonymous Inner Classes And Lambda Expressions
  • Switching Scenes
  • Creating Alert Boxes

Handle User Events

We have seen previously how to create a button on the scene. But it did nothing when we clicked it. Lets add a functionality to it by handling the click event on the button.

Replace the previous Main.Java with the following:

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

public class Main extends Application implements EventHandler<ActionEvent> {

    Button button;

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

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Title of Window");
        button = new Button();
        button.setText("Hey baby");

        //This class will handle the button events
        button.setOnAction(this);

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

    //When button is clicked, handle() gets called
    //Button click is an ActionEvent (also MouseEvents, TouchEvents, etc...)
    @Override
    public void handle(ActionEvent event) {
        if (event.getSource() == button) 
            System.out.println("Hey Charlie!");
    }

}

We have implemented EventHandler interface in the Main.java this time. So this class can simply handle all the events for the scene.

We need to override the hande() method of the EventHandler interface in Main class. This method handles all type of events for the application. So we need to check which on which layout has the current event occured.  So we added a check for the button  in the handle() method for all the events called on buttons.

Now run the Main.Java file as Java Application and click on the button. You will see ‘Hey Charlie!’ printed on the console.

Thus we have handled click events for the button.

 

Handle Click event JavaFX

Anonymous Inner Classes And Lambda Expressions

The above example we saw for event handling had too much work to be done for just a single event.  Lets look at a different implementation for the same task as before using Lambda Expressions

Replace the Main.Java file 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 {

	Button button;

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

	@Override
	public void start(Stage primaryStage) {
		primaryStage.setTitle("Title of Window");
		button = new Button();
		button.setText("Click Me");

		button.setOnAction(e -> {
			System.out.println("dsa dsa dsa !");
			System.out.println("Lambda expressions are awesome!");
		});

		/*
		 * button.setOnAction(new EventHandler<ActionEvent>() {
		 * 
		 * @Override public void handle(ActionEvent event) {
		 * System.out.println("Handle event using anonymous inner classes"); }
		 * });
		 */

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

}

Look at the commented section of the code above. The commented section is another way of doing the same EventHandling using anonymous class. You might be already familiar with that method.
The uncommented setOnAction() method which has been called uses Lambda Expressions for quickly handling the event. This feature has been added in JDK8 only.  So you might face syntax errors if you are using lower versions of JDK.

Switching Scenes

Now lets learn about changing the scene i.e whole layout of the stage of our application. Its similar to switching fragments in an Android Application.

For example : You click a button to go to next page or previous page.

Now Replace the Main.Java with:

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

public class Main extends Application {

    Stage window;
    Scene scene1, scene2;

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

    @Override
    public void start(Stage primaryStage) {
        window = primaryStage;

        //Button 1
        Label label1 = new Label("Welcome to the first scene!");
        Button button1 = new Button("Go to scene 2");
        button1.setOnAction(e -> window.setScene(scene2));

        //Layout 1 - children laid out in vertical column
        VBox layout1 = new VBox(20);
        layout1.getChildren().addAll(label1, button1);
        scene1 = new Scene(layout1, 200, 200);


        //Button 2
        Button button2 = new Button("This sucks, go back to scene 1");
        button2.setOnAction(e -> window.setScene(scene1));

        //Layout 2
        StackPane layout2 = new StackPane();
        layout2.getChildren().add(button2);
        scene2 = new Scene(layout2, 600, 300);

        //Display scene 1 at first
        window.setScene(scene1);
        window.setTitle("Title Here");
        window.show();
    }

}

VBox is another type of layout similar to Stackpane. VBox stands for Vertical Box. HBox stands for Horizontal Box. VBox adds Layouts in vertically stacked manner while HBox adds layout in horizontal way.

scenes JAVAFX

Look at the above two screenshots for the scenes. You can also change the resolution of the scene when switching.

Creating Alert Boxes

Lets create alert box in our applicaton.

  • Alert Boxes are used for showing a warning dialog.
  • Opening settings window and so on..

Alert box in JavaFX is simply another window similar to our original window of the application itself.

Create a new Class named AlertBox.java :


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

public class AlertBox {

    public static void display(String title, String message) {
        Stage window = new Stage();

        //Block events to other windows
        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle(title);
        window.setMinWidth(250);

        Label label = new Label();
        label.setText(message);
        Button closeButton = new Button("Close this window");
        closeButton.setOnAction(e -> window.close());

        VBox layout = new VBox(10);
        layout.getChildren().addAll(label, closeButton);
        layout.setAlignment(Pos.CENTER);

        //Display window and wait for it to be closed before returning
        Scene scene = new Scene(layout);
        window.setScene(scene);
        window.showAndWait();
    }

}
1

This class can simply be used whenever and wherever you need an alertBox to be shown.
Lets show the alert Box in Main.java:
1
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("Tutorials Face");
        button = new Button("Click Me");

        button.setOnAction(e -> AlertBox.display("Title of Window", "Wow this alert box is awesome!"));

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

}

We have simply called the static method defined in AlertBox.java to show a new window.
ALERT Box JavaFX

Look at the above screenshot how the alertBox is displayed as a new window.
The layout can always be made beautiful :p

We will see the remains topics in the next part.

8,472 total views, 1 views today

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

Today  we will use Java for developing cross-platform applications/softwares which can be run on Windows, Mac os, Linux etc.  You need to install Java Runtime Environment in the Operating System where you want to run your java based software application.

PreRequisite:

  • Basic knowledge of Java Programming.
  • Basic understanding of Object Oriented Programming.
  • JDK8 installed on working Operating System. Download if not from here.
  • Eclipse IDE

As you are already familiar with Java/ C++ Programming, you might have seen that those applications run in a console that looks like cmd / terminal etc. But now we will see how to develop an application which has a graphical user interface using Java.

All the programming goes same as the normal console app which you might have been already familiar with except for the GUI part. We will use JavaFX for integrating graphical UI in our java based software.

What is JavaFX?

JavaFX is a java library which provides APIs used for developing UI elements in a java application similar to Swing API. JavaFX is the latest library which has solved the problem of bad looking applications or say which has replaced the old windows 98 style look of java based softwares with a highly advanced client rich application’s look and feel. The apps developed using JavaFX can be given beautiful interface with as ease as building a website. It also supports CSS!  You can visit this for more information about JavaFX.

Table of Contents

  • Creating A Simple Window
  • Handle User Events
  • Anonymous Inner Classes And Lambda Expressions
  • Switching Scenes
  • Creating Alert Boxes
  • Communicating Between Windows
  • GridPane
  • Extract And Validate Input
  • CheckBoxes
  • ChoiceBox DropDown List
  • ComboBox
  • ListViews
  • TreeView
  • TableView
  • TableView Adding And Deleting
  • Menus
  • CSS
  • Properties
  • Binding
  • Fxml

Lets Begin..

Creating A Simple Window

We will be using eclipse IDE for this tutorial. So create a new Java Project in eclipse and name it anything.

Sample JavaFx App

Please note that in the JRE section of New Java Project Window, you have to set JAVA SE 8 or above as specified in the above screenshot.

Now go to the src folder of your project and create a new class named Main.Java with the following content :

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); // It calls start method defined bellow...
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        window = primaryStage;
        window.setTitle(" TutorialsFace - JavaFX");
        // Creating a simple UI button
        button = new Button("Click me");
        // StackPane is a type of layout which we will look at later..
        StackPane layout = new StackPane();
     
        //Adding the button to the layout
        layout.getChildren().add(button);

        // Create scene with resolution of 300x250 and add layout to it...
        Scene scene = new Scene(layout, 300, 250);

        // Add scene to the stage i.e to the window
        window.setScene(scene);
        window.show();
    }
}

Now right click on the Main.java and run as Java Application.

layout JAVAFX

The Scene and Stage can be understood in the screenshot above.

So this is the very basic application with a Graphic User Interface which does nothing :p

We will see the rest tutorial in the next part.

22,955 total views, 6 views today

Ball Hunt

ball hunt android game

Ball Hunt is a very simple arcade dots shooting game using stones and a sling shot. Different arrangements of dots are placed in a beautiful pattern for every new level.

Shoot and destroy these beautiful designs of bubbles and break the bubble using your slingshot shooting skills.
If you miss a target dot, the score multiplier gets reset. And for the continuous shots the multiplier get incremented by 1 irrespective of game mode.

GAME MODES ( HOW TO PLAY ):

1. CLASSIC:
You have got thirty seconds to score as high as you can. You get +1 second of bonus time as well as +1 multiplier for every hit after ten contiguous shots of bubble. If one shot is missed then the multiplier changes back to one.

2. LEVELS :
Its a level game. Fixed number of stones are provided for every level. If you are unable to shoot all the circles of a level using the provided number of stones, the game is over. Clear as many levels as possible.

Compete with your Facebook friends for high score.

Its a top free arcade bubble shooting game from the developers (Marothia Techs) of Shoot Girl’s Fruits, Gate Puzzle, Glassy Path and many more.

 

DOWNLOAD:

Google Play: https://play.google.com/store/apps/details?id=com.marothiatechs.ballhunt

AppStore: https://itunes.apple.com/us/app/ball-hunt-gulel/id1137944979?mt=8&ign-mpt=uo%3D4

2,066 total views, no views today

Gulel Craft : Knock Down

 

gulel craft

Gulel Crafts is a slingshot shooting game again from the makers of Shoot Girl’s Fruits : Gulel.
In this game you need to knock down the boxes, glasses, balloons, stones, all of them which are put as stack in the environment. There are different levels with unique arrangement of the object. Just smash them to the ground to clear each level.
[Online Map Store]

– There is an inbuilt map editor to create your own levels and let the world play them.
– Google Plus ID is used by default when uploading new levels.
– Play thousands of innovative levels created by other players.

Download Android: https://play.google.com/store/apps/details?id=com.marothiatechs.gulelcraft

3,566 total views, 1 views today

Implementing Remove Ads in app Purchases in Android Tutorial Example

In this tutorial we will quickly setup and integrate in app purchases in Android Apps/Games.

Steps needed for Implementation:

  1. Adding In App Billing Library using Android SDK Manager
  2. Setting up Google Play Developer Console
  3. Getting Required keys from Developer Console.
  4. Coding part

A Little Overview about how Google Play in-app purchases work

Before we begin, we need to know about how actually android in-app purchases work. In Android in-app purchases are made using either in app Billing Library OR Android Pay.

Android Pay:
Android Pay is used as wallet for making payments of non- digital goods. Its NOT of our use right now. You can learn more about it here.

In-App Billing:

In-app Billing is a Google Play service that lets you sell digital content from inside your applications. Thats what we will use today.





How in-app Billing actually works:

When making an in-app purchase, you actually buy a product from google. Consider it as a marketplace similar to Amazon where a seller puts his products for sale and users buy it from there. Similarly a developer needs to add a product in his developer console of his particular app. For example “Remove Ads” is a product which is added in the Google Play developer console for a particular app. When users pay for removing ads for a game/app, they actually buy the product from Developer Console of the developer.

Lets talk about the type of products. There are mainly two types for products in Android in app Billing.

  1. Managed Product – Its a type of product which a buyer pays for once. In other words, buyer owns the product for lifetime after making the purchase, and he cannot buy that same product ever again. If developer has given an interface to buy the same product again, it will throw an error. But these products can also be set as consumed for a particular buyer. And a consumed product can be bought again!

    Example of Consumable Managed Product:
    For example when a user buys a pack of 600 gems in a game, he buys a product named “600 Gems“. But as soon as the user buys 600 gems, this product is set as consumed so that it can be purchased again.

    Example of Simple Managed Product:
    This is a simple purchase of Managed Product. For example a user buys “Remove Ads” product which has to be owned for life time. So it cannot be purchased again by the same user. Developer do not write any code for consuming the product after purchase.

  2. Subscription – The name itself says it all. It a subscription of any service. For example a purchase for unlimited fuel for one month in car racing game (Example of the Sample In App Billing App provided by Google).

Lets Begin…

Adding In App Billing Library using Android SDK Manager

Step 1) Download Billing Library from Android SDK Manager as shown below:

Download Android in app billing library

Thats it! Rest we will see in the coding part 🙂

Setting up Google Play Developer Console

Step 1) Login to Google Play Developer Console and select YOUR_APP-> in-app Products. You need to setup merchant account for in-app billing. Its a simple form you need to fill. Then for adding products there, you need an apk with required Billing permission to be uploaded in the Developer console. So simply modify your exiting app’s AndroidManifest.xml file to add the following permission and upload that apk to alpha or Beta Testing :

    <uses-permission android:name="com.android.vending.BILLING" />

Step 2) Now you are eligible to add a product as in-app Product for your app. So add a product named “Remove Ads” as a Managed Product and provide other necessary details.

Step 3) Now add test users for making test purchases for your product by going to Developer Console-> Settings -> Account Details. Look at the image shown below.

Integrating In app purchases in android

Getting Required keys from Developer Console

Step 1) Note down the Product ID which you provided for the new product.

Step 2) Note down the Public Key of the app in which you are integrating in app billing. This can be obtained by going to Developer Console-> YOUR_APP-> Service & Apis. Look at the screenshot below:

Integrating In app billing Android

Coding part

Step 1) Open the sample app provided along with the in-app billing library you downloaded from Android SDK Manager. It will be located at : ANDROID_SDK_LOCATION/extras/google/play_billing

Lets look at the java classes provided in the Sample app:
In App Billing Sample App

Step 2) Create a new Package named com.android.vending.billing in your Android app and copy the file from the Sample app to your project’s this newly created package. Look below how I added this to my own project:

Inapp Billing File Copy

Step 3) Now Copy the complete package named “com.example.android.trivialdrivesample.util” along with its all java files to your own project. You can rename this package. These java files are required for in-app billing. You have to use them as it is for any project which requires in-app purchase integration.

Step 4) Now let do the final Integration of the in app purchases!

Create a new File named MyBillin.java with the following content:

package com.marothiatechs.apis;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.util.Log;

import com.marothiatechs.ZBHelpers.Constants;
import com.marothiatechs.gatepuzzle.billing.utils.IabHelper;
import com.marothiatechs.gatepuzzle.billing.utils.IabResult;
import com.marothiatechs.gatepuzzle.billing.utils.Inventory;
import com.marothiatechs.gatepuzzle.billing.utils.Purchase;

public class MyBilling {
	// Debug tag, for logging
	static final String TAG = "GatePuzzle";

	static final String SKU_REMOVE_ADS = "YOUR_PRODUCT_ID";

	// (arbitrary) request code for the purchase flow
	static final int RC_REQUEST = 10111;

	Activity activity;

	// The helper object
	IabHelper mHelper;

	String base64EncodedPublicKey = "YOUR_PUBLIC_KEY";
	Boolean isAdsDisabled = false;
	String payload = "ANY_PAYLOAD_STRING";

	public MyBilling(Activity launcher) {
		this.activity = launcher;
	}

	public void onCreate() {

		// Create the helper, passing it our context and the public key to
		// verify signatures with
		Log.d(TAG, "Creating IAB helper.");
		mHelper = new IabHelper(activity, base64EncodedPublicKey);

		// enable debug logging (for a production application, you should set
		// this to false).
		mHelper.enableDebugLogging(false);

		// Start setup. This is asynchronous and the specified listener
		// will be called once setup completes.
		Log.d(TAG, "Starting setup.");
		mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
			public void onIabSetupFinished(IabResult result) {
				Log.d(TAG, "Setup finished.");

				if (!result.isSuccess()) {
					// Oh noes, there was a problem.
					// complain("Problem setting up in-app billing: " + result);
					return;
				}

				// Have we been disposed off in the meantime? If so, quit.
				if (mHelper == null)
					return;

				// IAB is fully set up. Now, let's get an inventory of stuff we
				// own.
				Log.d(TAG, "Setup successful. Querying inventory.");
				mHelper.queryInventoryAsync(mGotInventoryListener);
			}
		});
	}

	// Listener that's called when we finish querying the items and
	// subscriptions we own
	IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
		public void onQueryInventoryFinished(IabResult result,
				Inventory inventory) {
			Log.d(TAG, "Query inventory finished.");

			// Have we been disposed of in the meantime? If so, quit.
			if (mHelper == null)
				return;

			// Is it a failure?
			if (result.isFailure()) {
				// complain("Failed to query inventory: " + result);
				return;
			}

			Log.d(TAG, "Query inventory was successful.");

			/*
			 * Check for items we own. Notice that for each purchase, we check
			 * the developer payload to see if it's correct! See
			 * verifyDeveloperPayload().
			 */

			// Do we have the premium upgrade?
			Purchase removeAdsPurchase = inventory.getPurchase(SKU_REMOVE_ADS);
			Constants.isAdsDisabled = (removeAdsPurchase != null && verifyDeveloperPayload(removeAdsPurchase));
			removeAds();

			Log.d(TAG, "User has "
					+ (Constants.isAdsDisabled ? "REMOVED ADS"
							: "NOT REMOVED ADS"));

			// setWaitScreen(false);
			Log.d(TAG, "Initial inventory query finished; enabling main UI.");
		}
	};

	// User clicked the "Remove Ads" button.
	public void purchaseRemoveAds() {

		activity.runOnUiThread(new Runnable() {

			@Override
			public void run() {

				mHelper.launchPurchaseFlow(activity, SKU_REMOVE_ADS,
						RC_REQUEST, mPurchaseFinishedListener, payload);

			}
		});
	}

	public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + ","
				+ data);
		if (mHelper == null)
			return true;

		// Pass on the activity result to the helper for handling
		if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
			// not handled, so handle it ourselves (here's where you'd
			// perform any handling of activity results not related to in-app
			// billing...
			return false;
		} else {

			Log.d(TAG, "onActivityResult handled by IABUtil.");

			return true;
		}

	}

	/** Verifies the developer payload of a purchase. */
	boolean verifyDeveloperPayload(Purchase p) {
		String payload = p.getDeveloperPayload();

		/*
		 * TODO: verify that the developer payload of the purchase is correct.
		 * It will be the same one that you sent when initiating the purchase.
		 * 
		 * WARNING: Locally generating a random string when starting a purchase
		 * and verifying it here might seem like a good approach, but this will
		 * fail in the case where the user purchases an item on one device and
		 * then uses your app on a different device, because on the other device
		 * you will not have access to the random string you originally
		 * generated.
		 * 
		 * So a good developer payload has these characteristics:
		 * 
		 * 1. If two different users purchase an item, the payload is different
		 * between them, so that one user's purchase can't be replayed to
		 * another user.
		 * 
		 * 2. The payload must be such that you can verify it even when the app
		 * wasn't the one who initiated the purchase flow (so that items
		 * purchased by the user on one device work on other devices owned by
		 * the user).
		 * 
		 * Using your own server to store and verify developer payloads across
		 * app installations is recommended.
		 */
		return true;
	}

	// Callback for when a purchase is finished
	IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
		public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
			Log.d(TAG, "Purchase finished: " + result + ", purchase: "
					+ purchase);

			// if we were disposed of in the meantime, quit.
			if (mHelper == null)
				return;

			if (result.isFailure()) {
				complain("Error purchasing: " + result);
				return;
			}
			if (!verifyDeveloperPayload(purchase)) {
				complain("Error purchasing. Authenticity verification failed.");
				return;
			}

			Log.d(TAG, "Purchase successful.");

			if (purchase.getSku().equals(SKU_REMOVE_ADS)) {
				// bought the premium upgrade!
				removeAds();

			}
		}
	};

	private void removeAds() {
		isAdsDisabled = true;
	}

	// We're being destroyed. It's important to dispose of the helper here!

	public void onDestroy() {

		// very important:
		Log.d(TAG, "Destroying helper.");
		if (mHelper != null) {
			mHelper.dispose();
			mHelper = null;
		}
	}

	void complain(String message) {
		Log.e(TAG, "**** TrivialDrive Error: " + message);
		alert("Error: " + message);
	}

	void alert(final String message) {
		activity.runOnUiThread(new Runnable() {

			@Override
			public void run() {

				AlertDialog.Builder bld = new AlertDialog.Builder(activity);
				bld.setMessage(message);
				bld.setNeutralButton("OK", null);
				Log.d(TAG, "Showing alert dialog: " + message);
				bld.create().show();
			}
		});
	}

}

Replace the Strings:
YOUR_PRODUCT_ID with the product id you noted down.
YOUR_PUBLIC_KEY with public key you noted down.
ANY_PAYLOAD_STRING can be replaced with anything. It can even be left as it is.




Now lets see what we have actually done in the MyBilling.Java file.

We have created this separate file where all the billing related tasks can be done. It is separated from your app’s main activity. There are some methods similar to the names of an Activity’s default methods such as..
onCreate();
onDestroy();
onActivityResult();

Simply create an instance of MyBilling.java in your main Activity class and call the above methods at there respective places.

Now look at the method purchaseRemoveAds() This is the method which should be called when a user clicks on “Remove Ads” Button provided in by you in your app. Simply provide an interface for making a purchase and call this purchaseRemoveAds() to initiate the purchase flow.

Thats All! You can go through the code for better knowledge about how the in app purchase flow is working in the MyBilling.java file.

29,546 total views, 4 views today