Saturday, June 29, 2013

Create a Notepad with Javafx2 - The Layout

There are many things that a FX Application can do. Its features can be experienced when we start creating Applications and diving into the limitless creative abilities and features offered. Our motive here is also simple here. 

Lets start by creating a simple Application - Notepad. Yes, one of simplest yet a very useful application. 

There are many ways of creating a Notepad. I'll be using the following.



The detailed breakup of layout is shown below.




Let us know start writing the fxml code for all that we decided above. The code will be very simple and will contain only the layout of the application and nothing beyond that. The rest is parked for a later discussion. For now lets create the layout. 

Create a notepad.fxml file and start filling up as we have mentioned in the prototype above.

Now, creating a window will be handled in the Java code. Let's start by creating a BorderPane. BorderPane lays out children in top, left, right, bottom, and center positions.

Enter the following lines in your fxml file.

<BorderPane xmlns:fx="http://javafx.com/fxml">
        <top>
        </top>
<center>
<TextArea>
</TextArea>
</center>
</BorderPane>

The code is simple. We are adding a BorderPane. We need a top and center placement and hence the elements 'top' and 'center'. 
Now we have to fill up top placeholder. Looking back at the  requirement we are supposed to add a MenuBar. Easy. Javafx helps us with this as well. 

       <top>
<MenuBar>
<menus>
<Menu text="File">
<items>
<MenuItem text="New"></MenuItem>
<MenuItem text="Open..."></MenuItem>
<MenuItem text="Save"></MenuItem>
<MenuItem text="Save As..."></MenuItem>
</items>
</Menu>
<Menu text="Edit">
<items>
<MenuItem text="Undo"></MenuItem>
<SeparatorMenuItem></SeparatorMenuItem>
</items>
</Menu>
</menus>
</MenuBar>

</top>

Adding a MenuBar is simple. The entire container that holds your Menu is called a MenuBar. A MenuBar will contain Menu's which in turn will have different submenus called items. Fill up whatever Menu and items you need and complete the code.

Here is the fxml code that I have written.

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

<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.SeparatorMenuItem?>
<BorderPane xmlns:fx="http://javafx.com/fxml">
<top>
<MenuBar>
<menus>
<Menu text="File">
<items>
<MenuItem text="New"></MenuItem>
<MenuItem text="Open..."></MenuItem>
<MenuItem text="Save"></MenuItem>
<MenuItem text="Save As..."></MenuItem>
<SeparatorMenuItem></SeparatorMenuItem>
<MenuItem text="Page Setup..."></MenuItem>
<MenuItem text="Print"></MenuItem>
<SeparatorMenuItem></SeparatorMenuItem>
<MenuItem text="Exit"></MenuItem>
</items>
</Menu>
<Menu text="Edit">
<items>
<MenuItem text="Undo"></MenuItem>
<SeparatorMenuItem></SeparatorMenuItem>
<MenuItem text="Cut"></MenuItem>
<MenuItem text="Copy"></MenuItem>
<MenuItem text="Paste"></MenuItem>
<MenuItem text="Delete"></MenuItem>
<SeparatorMenuItem></SeparatorMenuItem>
<MenuItem text="Find..."></MenuItem>
<MenuItem text="Find Next"></MenuItem>
<MenuItem text="Replace..."></MenuItem>
<MenuItem text="Go To..."></MenuItem>
<SeparatorMenuItem></SeparatorMenuItem>
<MenuItem text="Select All"></MenuItem>
<MenuItem text="Time/Date"></MenuItem>
</items>
</Menu>
<Menu text="Format">
<items>
<MenuItem text="Word Wrap"></MenuItem>
<MenuItem text="Font..."></MenuItem>
</items>
</Menu>
<Menu text="View">
<items>
<MenuItem text="Status Bar"></MenuItem>
</items>
</Menu>
<Menu text="Help">
<items>
<MenuItem text="View Help"></MenuItem>
<SeparatorMenuItem></SeparatorMenuItem>
<MenuItem text="About Notepad"></MenuItem>
</items>
</Menu>
</menus>
</MenuBar>
</top>
<center>
<TextArea>
</TextArea>
</center>
</BorderPane>


Fxml code is easy to understand. 
Remember to note the import statements like 
<?import javafx.scene.control.Menu?>

The fxml above is to be loaded by Java code as already mentioned in previous blogs. 
Here is the Java code for us. 

import java.io.IOException;

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

public class Launcher extends Application {

 @Override
 public void start(Stage primaryStage) {

  try {
   // loading the fxml
   Pane pane = FXMLLoader.load(getClass().getResource(
     "/fxml/notepad.fxml"));
   
   // creating and initializing the scene.
   Scene scene = new Scene(pane);
   primaryStage.setScene(scene);

   // setting the height and width of stage.
   primaryStage.setWidth(1024);
   primaryStage.setHeight(768);

   // setting the App title
   primaryStage.setTitle("Untitled - Notepad");

   // display the stage
   primaryStage.show();

  } catch (IOException e) {
   e.printStackTrace();
  }
 }

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


After we have finished, run the application. This is what we get as an output. Not much but we have managed at least the layout. looking at the code it cannot become simpler than this. 



So here we are with the layout of the App. Next we will try to add some css to  the application. 

Friday, June 14, 2013

Creating your first Javafx Program

The conventional way of starting is "Hello world!!!". Lets not do it and start off with something that just helps us going forward. 

I'll be using Eclipse for all my projects. Needless to mention, that the basics should be the same for any editor of your choice. Also, I'll be creating my projects using fxml (an xml representation of your UI). But this does not mean that you are limited to using the same. Javafx offers the very familiar swingy way of creating UI's as well. Why I prefer fxml is different story altogether. 

Create a JavaFX project in your eclipse. If you have downloaded e(fx)clipse you'll be able to view it in the new project wizard. You can refer to this post if you want to do the same. However, if not downloaded and you do not intend to as well then just create a java application and add jfxrt.jar in your project. You should find it in your jdk installation. if you don't want to include it in each and every time you create a project then you can default it in your eclipse.
  
Project Structure


My Project Structure looks something like this. 












Select Main Class





Go to src folder and right click to view the select wizard. Select Javafx Main Class as shown. Fill up a name and click finish. You should see a class created in the src folder. 
















After you have finished with the wizard, you will see a class file with the same skeleton structure as shown on the left. If you don't have e(fx)clipse installed the simply create a class and add the code as shown on the left. 







Creating the Main class

---------------------------------------------------------------------------------

import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class First extends Application {

@Override
public void start(Stage primaryStage) throws IOException {

//loading the fxml
Pane pane = FXMLLoader.load(getClass().getResource(""));

//creating and initializing the scene.
Scene scene = new Scene(pane);
primaryStage.setScene(scene);

//setting the height and width of stage.
primaryStage.setWidth(1024);
primaryStage.setHeight(768);

//setting the App title
primaryStage.setTitle("My first program");

//display the stage
primaryStage.show();
}

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

}

-----------------------------------------------------------------------

You should see an error when you try to run this. This is because you have not supplied the name of fxml when you are trying to load the fxml. Change the line to 

Pane pane = FXMLLoader.load(getClass().getResource("first.fxml"));

Now you should be creating the fxml file. 
Right click on the src folder and select the Javafx wizard in the same way you did above. Select New fxml document. Add a name to the fxml document you wish to create and supply the same name to the FXML loader in the main class. 


Creating the fxml file

---------------------------------------------------------------------------------

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

<?import javafx.scene.layout.BorderPane?>

<BorderPane xmlns:fx="http://javafx.com/fxml">
<!-- TODO Add Nodes -->
</BorderPane>

---------------------------------------------------------------------------------

Now your set to go. Run you main class and you should be able to see the stage. Your stage should be something like this

First Stage


That's it. This looks very simple as compared to a lot many programs that I have written for the same purpose.  My choice was fxml, but if you want you code your ui in the classes as well. Simple yet powerful and that is what Javafx2 is all about.  

Wednesday, June 12, 2013

Eclipse Project Structure - Javafx2

Creating Applications in Javafx2 is simple. Creating using Eclipse is simpler. It gives you the features of Auto Completion, error highlighting etc. Moreover, it gives you the chance of working with your favourite IDE.  

Open Eclipse and change perspective to Java (not required though). 
Right Click on your package explorer view or navigator view if  you like to work on it. From the pop menu that just opened, select New -> Other

JavaFX Wizard




You should be able to locate JavaFX in the Popup Menu. Select JavaFX Project under the same. 
If you are not able to locate JavaFX it means you have not installed e(fx)clipse plugin. Refer to prev blog if you want to.








The next opens a New Project Wizard. Supply the project Name and you should be good. 

Next step create your project structure the way you like. My project structure structure looks something like below.

Project Structure




1. lib : store your jars here
2. src : store your java files here
3. build : FX project build. 
4. resources : store stuff apart from java files. 

But you are free to create your own structure. The structure here does not matter much as hence you can keep it the way you are used to.


Saturday, June 8, 2013

JavafX2 setup using Eclipse/Netbeans

Setting up an Eclipse Project for JavaFx2 is easy. Although Netbeans is fully equipped with everything you'll need for creating and running a Javafx2 App, I still use Eclipse. Reason, I am more used to Eclipse than Netbeans. But there is always a reason to try.

The first step would be to download and install the JDK on your system. Make sure you have setup the PATH and JAVA_HOME env variables. 

I am currently using JDK7 u21 on my system as shown below. JavaFx2 Comes packaged with this version. if you are using jdk 1.6 then you'll have to download JavafX2 separately and install it. I recommend upgrading your JDK.

Second, install Eclipse. This should be easy again. All you need to do is download a zip file and unzip it in your local drive. 

Third, download the JavaFX Scene Builder. Scene Builder is an amazing tool provided for building JavaFX2 layouts without any coding. It is as easy as simple drag and drop.  

Fourth, install e(fx)clipse in Eclipse. You can read about the same here. Downloading and installing is easy. Just follow the instructions mentioned in the site and you'll be good.

You are ready to start now. If you actually want yourself to save this trouble just download Netbeans and start coding. All you'll need is a scene builder and that's it. so go ahead, take your pick, Netbeans or eclipse all up to you.

We are all set now. Eclipse and Netbeans doesn't really matter.
  

Thursday, June 6, 2013

Why JavaFX2

This is in continuation to prev post "Which Language to choose for a User Interface". I had mentioned something about JavaFx. I was instantly withdrawn towards FX2 the moment I started reading about it. I wanted to try it, and so I checked how to install the same. At that time I could spot certain DLL's etc. that were shipped with FX2. Now, all that you have to do to install the latest JDK and you have it. 

What is JavaFX2?

Quoting from WIKI- JavaFX is a software platform for creating and delivering rich internet applications (RIAs) that can run across a wide variety of devices. The current release has support for desktop computers and web browsers on Windows, Linux, and Mac OS X.
Sun- JavaFX 2 is the next step in the evolution of Java as a rich client platform, shortening development time and easing deployment of data-driven business and enterprise client applications.
The JavaFX2 Documentation - JavaFX is a set of graphics and media packages that enables developers to design, create, test, debug, and deploy rich client applications that operate consistently across diverse platforms.

Overview of JavaFx2 in the JavaFx2 documentation establishes many benefits of using Javafx2 over many languages. It is a must read even for those who have not read it before. 

Why JavaFx2 though? the question is pretty obvious and is most important here to be discussed. 

I always thought that why cant a Web APP kind of UI be applied to Desktops. I mean layouts using a "View", decorating using css, events using scripts etc. This had to be simple and still was not available. Why do I have to learn two different things, one to create a Web Application and the other to create a Desktop Application. My questions were answered when FX2 came into picture.  
As a Java developer working on Web Apps, I always wanted a similar technology for Desktop Apps. 

Working on Java, there has been many occasions where I needed to build a GUI application. There were options like Swing, SWT etc. I would mention that  Swing is great for UI development. I created all my college apps in Swing, also my intern-ship project was in Swing. But, soon I realised that trends changed over time. There was a need for something different. Much more different than what technology like Swing offered. For example why do an interactive developer need to learn how to code in Java to develop a UI of an App. With the way user Interfaces are being developed these days, you need experts to give you that jazzy feel about your App. Is this possible in Swing? Of course it is, but imagine the time both a Java developer and an UI developer will have to spend together to come up with the same. Anyway, lets   say you learnt Swing and Java and started creating Apps. Now as a Client, I want you to create a web APP as well. Now what? start learning HTML/CSS and what not. What about a mobile App. Javafx2 aims to resolve these issues. Also, it is easily integrable with Swing.

FX2 has many advantages. It can exploit the power of Java by referencing API's from Java library. Look and Feel of FX2 applications is highly customizable as it can be done using CSS. Layouts can be created using fxml file that is xml based and hence separate from coding. JS files can be included to capture events. This just doesn't end here. FX2 has lot of other benefits as well like its light weight. FX2 can be incorporated in an IDE like eclipse and comes default with Netbeans. These are very powerful IDE's and help a lot during development. For designing UI, Scene Builder can be downloaded and integrated as well with your IDE's. All of these are freely available.

So you got portability, readability, ease of development and faster development. You get an uniform language for all possible devices. You get integration with Swing. You get the power of Open source as well. What else could one ask for? You get to create the most amazing Apps in one of the most used language and huge number of people to help you worldwide in case you are stuck. 

If you want to see the full capability of Javafx please visit the sample page.




Which Language to choose for a User Interface

I do not have much of an industry experience when Desktop Applications are concerned. Whatever I learnt, I learned as a hobby. I still remember me wondering if I could build desktop applications the way professionals did. I started computers by learning C++.

I have worked on both Web Applications as well as Desktop Applications using J2EE and related technologies. There was one thing very clearly stated - you can not live in both the worlds. I always challenged the notion and worked equally in both these different ways of programming. Though it gives me a great sense of control over the language Java (at least id like to think this way), but I'll take it, it was never that easy.

I'll take a step back and also mention that Java has a very strong framework for building GUI's called Swing. I created some applications using it. It is just like creating any other simple Java application. No extra dependencies, and you have the world at you, creativity has no limits. Just that I found Swing getting bit difficult as an when the complexity of the Application increases. Dividing each UI component into different classes, making sure that they interact well, mapping heavy models with UI etc. 


The world looked content with Java Swings, but still people prefer technologies like Adobe flex for Desktops Apps. According to Oracle, the Java Runtime Environment is found on over 850 million PCs (source: wiki). Then why is such a powerful language not the current favourite for creating desktop Apps. Even if we consider web browsers, then, Java is installed on roughly 70 percent of Web browsers, which makes it the second most popular plugin behind Adobe Flash, and places it before heavyweights such as Quicktime, Windows Media Player, or Silverlight. Java is also popular on mobile devices. 

If a language that has such a deep penetration worldwide, why is it not the very best choice for creating user interfaces. What could be the possible pull backs that stops a developer from exploring the real power of Java. Is the applications difficult to design? Does it weigh too much on a developer to convert artefacts from creative into Java? Is it heavyweight for real complex applications and hence slow for a real smooth user experience. I can say these could be issues for a poorly designed application. But the question that comes to me is how often can an application be a victim of not such a good design? How easily the application is susceptible to an improper or well thought off design? Many Swing developers will argue that Sky is the limit for them. True, I thought the same way until I learned Adobe Flex just to 

Going through the software available in the market for Application development, I could come up with some very good options. There are many  languages available today and I am pretty sure most of them will live up to the criteria of being a language that helps creating good Apps. There are languages like Java, python, VB.NET, C#, C++ and QT framework,  Adobe AIR etc. The list goes on. Now, .Net and Java languages run on JVM's while languages like C++ and QT run on Native OS. So definitely using Adobe AIR and C++ with QT is faster than languages that run using JVM's. Then why not use the native languages themselves and finish off the debate for once. The trade off is portability. There is a huge debate on using cross platform languages. The more the number of devices the more platform independent the application is expected to be. The obvious question that comes to your mind "Should the performance and efficiency be compromised for a want of portability"? There are a lot of topics that come to your mind when you rate a language - 

  1. Memory Management
  2. Readability
  3. Ease of learning
  4. Ease of understanding
  5. Speed of development
  6. Help with enforcement of correct code
  7. Handle complexity - algorithms etc.
  8. Performance of compiled code
  9. Fit-for-purpose
  10. Lines of code
  11. Supports Object Oriented
  12. Easier scalability of Apps
  13. Supporting IDE

The list (not in order - of course) is huge and what not could be included here. But that is not our motive here. The features that separates languages should be the determining factor. Starting with .Net related languages, these are great. I cannot help but mention that fact that I started my carrier by leaning C#, ASP.Net etc. Visual studio is a great IDE to work and helps improve the readability and hence the Speed of development is relatively good. It has a great MSDN library for reference and hence help is available. The drawback is Visual Studio 2012 is not free. There goes a lot of quotient related to readability etc. Something bigger that is the cause of concern is portability. Although, I am big fan of open source languages but I leave it on the reader to decide on the same. For me it goes 3 points down. A great language, great  documentation though.

Moving to Adobe AIR, the language is great. I learnt the language myself and found the real beauty of the same. When I started learning Adobe flex the concept of creating a xml based ui was very new for someone like me. It was the best way of creating a UI. Without contention I can state that Flex is still a amazing way of creating an App. The creative possibility for flex is unlimited. Adobe supplies an IDE for flex called as FlexBuilder that helps achieve various other features like ease of development,  readability etc. the concert of calling a script for events is a very smart way of achieving the event handling. Although flex may have huge capabilities as a language it comes with  SWF file that needs to be downloaded on a page load (increases onload performance , Desktop applications would require a Adobe AIR runtime to be installed. This may not be a big issue except that it is not generally found in client machines.
A drawback for the language, Flex Builder is not free and hence it shares some of the problems with .Net languages. Also, to use powerful features of languages like Java and .net, flex does provide integration plugins, useful feature but I suppose this might make connections slower between the two talking modules (Although I do not have enough evidence to substantiate the same). To conclude Flex, although portable, there are still some problems that stops me from diving into the same. 


Now languages like C++ and QT are of a different genre themselves. They are fast, give a lot of control to the programmer, even to a level that he can manage memory by himself. But then with great powers comes greater responsibilities. The more complex your code starts looking. Anyway, not considering that as a drawback because that goes on the developer himself and his capabilities. Portability, can that be a issue? Of course, that is one. But not sounding judge mental enough, this language is definitely the greatest so far. Its fast, gives more control etc. etc. we know it all. But honestly I have worked on C++ in my college and I find it better than many languages that I know off today. I leave it to the readers to decide. For me, I'll always choose a language that I am comfortable with and that meets all my requirements. At present I have not worked on C++ as a user interface language and hence not commenting on it. 

There are so many drawbacks in every language and advantages as well. Thinking about the same I stumbled upon Javafx2. TBC...