<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; Java FX</title>
	<atom:link href="http://www.javabeat.net/category/javafx-2/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Thu, 23 May 2013 01:30:53 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Using Lambda Expressions of Java 8 in Java FX event handlers</title>
		<link>http://www.javabeat.net/2012/05/using-lambda-expressions-of-java-8-in-java-fx-event-handlers/</link>
		<comments>http://www.javabeat.net/2012/05/using-lambda-expressions-of-java-8-in-java-fx-event-handlers/#comments</comments>
		<pubDate>Mon, 14 May 2012 02:20:45 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java 8.0]]></category>
		<category><![CDATA[Java FX]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[Project Lambda]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3690</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Note: The Project Lambda (JSR-335) to be added in Java 8 is evolving and the sample here is how one can use Lambdas with the current Java8 build downloaded from here. I will try to update the sample if there are any changes in the API in future. I thought it will be good to [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p><em>Note: The <a href="http://openjdk.java.net/projects/lambda/" title="Project Lambda" target="_blank">Project Lambda (JSR-335)</a> to be added in Java 8 is evolving and the sample here is how one can use Lambdas with the current Java8 build downloaded from <a href="http://jdk8.java.net/lambda/" title="Java 8 Binaries" target="_blank">here</a>. I will try to update the sample if there are any changes in the API in future</em>. </p>
<p>I thought it will be good to get a peak of how Lambda Expressions can be used with JavaFX or for that matter any Single Abstract Method (SAM) types. </p>
<p>Lets build a sample with just one toggle button and change the text of the toggle as and when it is selected/un-selected.<br />
<a href="http://www.javabeat.net/wp-content/uploads/2012/05/javafxLambda1.png"><img src="http://www.javabeat.net/wp-content/uploads/2012/05/javafxLambda1.png" alt="" width="206" height="206" class="aligncenter size-full wp-image-3691" /></a></p>
<p>The code with the current Java -7 version would be:</p>
<pre class="brush: java; title: ; notranslate">
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleButtonBuilder;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class LambdasWithJavaFx extends Application {
  public static void main(String[] args){
    Application.launch(args);
  }
  @Override
  public void start(Stage stage) throws Exception {
    BorderPane root = new BorderPane();
    ToggleButton button = new ToggleButton(&quot;Click&quot;);

    final StringProperty btnText = button.textProperty();
    button.setOnAction(new EventHandler&lt;ActionEvent&gt;() {
      @Override
      public void handle(ActionEvent actionEvent) {
        ToggleButton source = (ToggleButton) actionEvent.getSource();
        if (source.isSelected()) {
          btnText.set(&quot;Clicked!&quot;);
        } else {
          btnText.set(&quot;Click!&quot;);
        }
      }
    });
  
    root.setCenter(button);

    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.setWidth(200);
    stage.setHeight(200);
    stage.show();
  }
}
</pre>
<p>The main focus would be on the EventHandler set for the ToggleButton, henceforth I would just show that part of the above code. </p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Lets see how we can use the Lambda expression to update above code. </p>
<pre class="brush: java; title: ; notranslate">
button.setOnAction((ActionEvent event)-&gt; {
  ToggleButton source = (ToggleButton) event.getSource();
  if (source.isSelected()) {
    btnText.set(&quot;Clicked!&quot;);
  } else {
    btnText.set(&quot;Click!&quot;);
  }
});
</pre>
<p>The only method in the EventHandler class is the handle(Event event) method and in the above example we just write the body and the parameter declaration for the method and remove all the unnecessary instantiation code. </p>
<p>We can remove the type declaration for the event, as the compiler will infer the type from the context. The context here is the Action event and hence the EventHandler expects a ActionEvent and thereby the event reference is inferred to be of ActionEvent type.</p>
<pre class="brush: java; title: ; notranslate">
button.setOnAction((event)-&gt; {
  ToggleButton source = (ToggleButton) event.getSource();
  if (source.isSelected()) {
    btnText.set(&quot;Clicked!&quot;);
  } else {
    btnText.set(&quot;Click!&quot;);
  }
});
</pre>
<p>This is just a peek at the Lambda expressions to be introduced in Project Lambda (JSR-335). I would take some time to dive a bit into detail of Lambda expressions. </p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fjavafx-2%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/javafx-2/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/javafx-2/feed/" data-count="vertical" data-text="Java FX" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/using-lambda-expressions-of-java-8-in-java-fx-event-handlers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Developing a Simple Todo Application using JavaFX, Java and MongoDB- Part-3</title>
		<link>http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-3/</link>
		<comments>http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-3/#comments</comments>
		<pubDate>Sun, 13 May 2012 16:42:22 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java FX]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[MongoDB]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3664</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In the previous post we created the UI for adding a new Todo where in we used a Tab, TabPane and added the required controls- TextField and a Button to the Tab. Going forward, in this post we will create the UI for listing the Open Todos i.e the Todos which have not been marked [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In the <a title="Developing a Simple Todo Application using JavaFX, Java and MongoDB- Part-2" href="http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-2/">previous post</a> we created the UI for adding a new Todo where in we used a Tab, TabPane and added the required controls- TextField and a Button to the Tab.</p>
<p>Going forward, in this post we will create the UI for listing the Open Todos i.e the Todos which have not been marked as Closed. We intend to implement the following features in the UI:</p>
<ul>
<li>Ability to load the Todos when the Tab is selected.</li>
<li>Obtain a list view for the Todos with a scroll bar if the list takes more vertical space than required.</li>
<li>For each Todo, provide a button to mark the todo as completed.</li>
</ul>
<div>
<p>Before going further, lets have a look at the possible UI we wish to generate at the end:</p>
<p style="text-align: center"><a href="http://www.javabeat.net/wp-content/uploads/2012/05/todoList.png"><img class="aligncenter" src="http://www.javabeat.net/wp-content/uploads/2012/05/todoList.png" alt="" width="227" height="348" /></a></p>
</div>
<h3>Loading the Todo on Tab selection:</h3>
<p>We add an EventHandler (class TodoLoader) which is added to the <a title="Tab- SelectionChanged" href="http://docs.oracle.com/javafx/2/api/javafx/scene/control/Tab.html#onSelectionChangedProperty" target="_blank">Tab#onSelectionChanged</a> event, which loads the Todos from the repository and creates a GridPane with the task name, date when it was added and the button to mark the Todo as completed. This button, which marks the Todo as closed, uses the CloseTodoHandler.</p>
<p><strong>TodoLoader</strong> and <strong>CloseTodoHandler</strong> implement <a title="EventHandler" href="http://docs.oracle.com/javafx/2/api/javafx/event/EventHandler.html" target="_blank">EventHandler</a> and the handle method is overridden to add the required functionality.</p>
<h4>Constructing the Handler for loading the Open Todos:</h4>
<p>In the TodoLoader#handle(Event event) method we:</p>
<p>Get all the open todos from the database:</p>
<pre class="brush: java; title: ; notranslate">
openTodos = TodoDAO.getOpenTodos();
</pre>
<p>For each Todo we have fetched, create a Label for task text and date added and a button for marking the todo as completed. Also for the button we set its actionEvent handler which is an instance of CloseTodoHandler.</p>
<pre class="brush: java; title: ; notranslate">
for(Todo aTodo : openTodos)
{
  GridPane todoPane = new GridPane();
  Label taskLabel = new Label(aTodo.getTask());
  Label dateAdded = new Label(aTodo.getAdded().toString());

  CloseTodoHandler closeHandler =
    new CloseTodoHandler(todoBox,
          todoPane,
          aTodo);
  Button closeButton  = ButtonBuilder.create()
      .graphic(new ImageView(
           new Image(getClass().getResourceAsStream(&quot;check.png&quot;))))
      .onAction(closeHandler)
      .build();

  todoPane.add(taskLabel,1,1,5,1);
  todoPane.add(dateAdded,1,2,4,1);
  todoPane.add(closeButton, 5, 2, 1, 1);
  todoBox.getChildren().add(todoPane);
}
</pre>
<p>The code for the complete class which loads the Todos and constructs the required UI is: </p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
class TodoLoader implements EventHandler&lt;Event&gt;{

  List&lt;Todo&gt; openTodos;   
  VBox todoBox;

  TodoLoader(VBox todoBox){
    this.todoBox = todoBox;
  }
  @Override
  public void handle(Event event) {
    //Clear the existing Todos, for adding new Todos
    todoBox.getChildren().clear();
    try {
      openTodos = TodoDAO.getOpenTodos();
      for(Todo aTodo : openTodos)
      {
        //A component that displays the information for each todo
        GridPane todoPane = new GridPane();
        Label taskLabel = new Label(aTodo.getTask());
        Label dateAdded = new Label(aTodo.getAdded().toString());

        //Event handler for handling close operations
        CloseTodoHandler closeHandler =
            new CloseTodoHandler(todoBox,
                todoPane,
                aTodo);
        Button closeButton  = ButtonBuilder.create()
            .graphic(new ImageView(
                     new Image(getClass().
                               getResourceAsStream(&quot;check.png&quot;))))
            .onAction(closeHandler)
            .build();

        /*
         * Add the task label,
         * date added, and the 
         * close button to the 
         * gridpane component
         */
        todoPane.add(taskLabel,1,1,5,1);
        todoPane.add(dateAdded,1,2,4,1);
        todoPane.add(closeButton, 5, 2, 1, 1);
        todoBox.getChildren().add(todoPane);
      }
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
  }
}
</pre>
<p>Now, lets look at some aspects of the CloseTodoHandler. </p>
<h4>Constructing the handler for closing the Todos:</h4>
<p>Each button which handles closing of todo should be aware of:</p>
<ul>
<li>which Todo to close i.e have a reference to the Todo instance</li>
<li>which GridPane to remove from the VBox, should have a reference to GridPane instance</li>
<li>which VBox to remove from i.e reference to the VBox instance. </li>
</ul>
<p>When we are creating the instance of the CloseTodoHandler, we pass in these information as shown</p>
<pre class="brush: java; title: ; notranslate">
CloseTodoHandler closeHandler = 
    new CloseTodoHandler(todoBox,
                         todoPane,
                         aTodo);
</pre>
<p>In the handling of this event: we just have to invoke the corresponding DAO method to close the Todo and also remove it from the VBox as shown below:</p>
<pre class="brush: java; title: ; notranslate">
@Override
public void handle(ActionEvent actionEvent) {
  try {
    TodoDAO.setTodoAsCompleted(todo);
    todoBox.getChildren().remove(todoPane);
  } catch (UnknownHostException e) {
    e.printStackTrace();
  }
}
</pre>
<p>The complete code for the <strong>CloseTodoHandler</strong> is:</p>
<pre class="brush: java; title: ; notranslate">
class CloseTodoHandler implements EventHandler&lt;ActionEvent&gt;{

  VBox todoBox;
  GridPane todoPane;
  Todo todo;

  CloseTodoHandler(VBox todoBox,
                   GridPane todoPane,
                   Todo todo){
    this.todo = todo;
    this.todoBox = todoBox;
    this.todoPane = todoPane;
  }
  
  @Override
  public void handle(ActionEvent actionEvent) {
    try {
      TodoDAO.setTodoAsCompleted(todo);
      todoBox.getChildren().remove(todoPane);
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
  }
}
</pre>
<p>Now we have to build the Tab which uses all the above classes, event handlers to generate the UI as shown in the screen shot above. An instance of VBox is created to add all the Todos on the UI and this instance is passed to the TodoLoader class so that it can use it to populate the UI as shown above in the TodoLoader class definition.</p>
<pre class="brush: java; title: ; notranslate">
final VBox todoBox = new VBox();
todoBox.setTranslateX(10);
todoBox.setSpacing(10);

</pre>
<p>As the items can occupy more than the given height of the application, we use <a href="http://docs.oracle.com/javafx/2/api/javafx/scene/control/ScrollPane.html" title="ScrollPane" target="_blank">ScrollPane</a> to add the Veritcal scroll bars:</p>
<pre class="brush: java; title: ; notranslate">
final ScrollPane todoListScroll = ScrollPaneBuilder.create()
    .hbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED)
    .prefHeight(APP_HEIGHT - 90)
    .maxWidth(APP_WIDTH)
    .build();
todoListScroll.setContent(todoBox);
</pre>
<p>And finally build the Tab as:</p>
<pre class="brush: java; title: ; notranslate">
Tab allTodosTab = TabBuilder.create()
    .text(&quot;All todos&quot;)
    .content(todoListScroll)
    .closable(false)
    .onSelectionChanged(new TodoLoader(todoBox))
    .build();
</pre>
<p>We refactor this code into a method and this method is invoked from the TodoAppRunner defined in the <a href="http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-2/" title="Developing a Simple Todo Application using JavaFX, Java and MongoDB- Part-2" target="_blank">previous post</a>. </p>
<pre class="brush: java; title: ; notranslate">
private Tab buildShowAllTodoUi(){
  final ScrollPane todoListScroll = ScrollPaneBuilder.create()
    .hbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED)
    .prefHeight(APP_HEIGHT - 90)
    .maxWidth(APP_WIDTH)
    .build();

  final VBox todoBox = new VBox();
  todoBox.setTranslateX(10);
  todoBox.setSpacing(10);
  todoListScroll.setContent(todoBox);

  Tab allTodosTab = TabBuilder.create()
   .text(&quot;All todos&quot;)
   .content(todoListScroll)
   .closable(false)
   .onSelectionChanged(new TodoLoader(todoBox))
   .build();

  return allTodosTab;
}
</pre>
<p>The complete source code can be downloaded from <a href="https://github.com/sanaulla123/TodoFX" title="TodoFX" target="_blank">here</a>. I know its been a long series of posts and if you are stuck at any point just let us know via the comments here and we would try to clear out the confusion.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-3/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Developing a Simple Todo Application using JavaFX, Java and MongoDB- Part-2</title>
		<link>http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-2/</link>
		<comments>http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-2/#comments</comments>
		<pubDate>Sat, 12 May 2012 11:08:26 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java FX]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[MongoDB]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3649</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In my previous post: I setup the objective of our sample application and named it as TodoFX (I know lot of you would have missed the naming part, lack of creativity in naming drives me create portmanteau of technology and usage of app) Created the back end for our sample application, in the process we [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In my <a title="Developing a Simple Todo Application using JavaFX, Java and MongoDB- Part-1" href="http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-1/">previous</a> post:</p>
<ul>
<li>I setup the objective of our sample application and named it as TodoFX (I know lot of you would have missed the naming part, lack of creativity in naming drives me create portmanteau of technology and usage of app)</li>
<li>Created the back end for our sample application, in the process we played around with MongoDB (not much though).</li>
</ul>
<p>Continuing with the application, I would like to:</p>
<ul>
<li>Add a few updates to the model and backend APIs we had created earlier</li>
<li>Develop the UI for our application. This would include 2 parts- Developing the UI for Adding new task and Developing the UI to list all uncompleted tasks.</li>
</ul>
<h3>Updates to the model and the backend APIs:</h3>
<p>I thought of introduing &#8220;id&#8221; field, and this would help us in identifying a particular Todo and mark it as completed. The updated Todo class would be:</p>
<pre class="brush: java; title: ; notranslate">
public class Todo{
  //Among other fields
  private String id;
  public String getId(){
    return id;
  }
  public void setId (String id){
    this.id = id;
  }
}
</pre>
<p>Lets also update the TodoDAO, to add a method to get incomplete Todos:</p>
<pre class="brush: java; title: ; notranslate">
public class TodoDAO{
  //Other methods defined in previous post
  public static List getOpenTodos()
    throws UnknownHostException{
    DB db = DbManager.getDb(DBNAME);
    DBCollection collection = db.getCollection(COLLECTION_NAME);
    DBObject filterObject = BasicDBObjectBuilder.start()
      .add(&quot;completed&quot;,false)
      .get();
    DBCursor dbCursor = collection.find(filterObject);
    List openTodos = new ArrayList();
    while ( dbCursor.hasNext()){
      DBObject dbObject = dbCursor.next();
      String task = String.valueOf(dbObject.get(&quot;task&quot;));
      Date added = (Date)dbObject.get(&quot;added&quot;);
      boolean completed = (Boolean)dbObject.get(&quot;completed&quot;);
      Todo todo = new Todo(task,
                           completed,
                           added,
                           dbObject.get(&quot;_id&quot;).toString());
      openTodos.add(todo);
    }
    return openTodos;
  }
}
</pre>
<p style="text-align: justify">One important take away in the above example is the use of a JSON object in the <a title="Mongodb Java API" href="http://api.mongodb.org/java/current/com/mongodb/DBCollection.html#find(com.mongodb.DBObject)" target="_blank">DBCollection#find()</a>, the JSON object which was passed is the query used for fetching the data. And how do you create the JSON object? Using BasicDBObject or DBObject.</p>
<p style="text-align: justify"><del datetime="2012-05-11T17:55:37+00:00">We might have to come back and update the DAO to add a method to set a selected task as completed. ( I am working on the UI to get it working well). </del>Ok, I just went back, tried out the API and here it is how we would update the Todo to set it as completed. We need a JSON object to identify what to update and then a JSON object to set the updated value for the attribute/key we want (and this is the reason why we added the &#8220;id&#8221; attribute in the Todo Model class). We will add the below method to the TodoDAO class (here I would independently give the method, but its a part of the TodoDAO class)</p>
<pre class="brush: java; title: ; notranslate">
public static void setTodoAsCompleted(Todo todoRef)
  throws UnknownHostException{
  DB db  = DbManager.getDb(DBNAME);
  DBCollection collection = db.getCollection(COLLECTION_NAME);
  DBObject queryObject = BasicDBObjectBuilder.start()
    .add(&quot;_id&quot;, new ObjectId(todoRef.getId()))
    .get();
  DBObject updateValue = BasicDBObjectBuilder.start()
    .add(&quot;completed&quot;,true)
    .get();

  collection.update(queryObject,updateValue);
}
</pre>
<p>We make use of <a title="DBCollection" href="http://api.mongodb.org/java/current/com/mongodb/DBCollection.html#update(com.mongodb.DBObject, com.mongodb.DBObject)" target="_blank">DBCollection#update(query,newValue)</a> to update the DB row/JSON object identified by the query.</p>
<p>That&#8217;s pretty much I had to add about back end, yeah I know you are more excited to see about JavaFX and the UI, so lets now create a simple UI. I am thinking splitting this UI into one more post and in this post I would explain about the UI for adding new task.</p>
<h3>Developing the UI for TodoFX &#8211; Add new Task UI:</h3>
<p>Once completed, the UI would look like:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/05/todofx_add.png"><img class="aligncenter size-full wp-image-3651" src="http://www.javabeat.net/wp-content/uploads/2012/05/todofx_add.png" alt="" width="221" height="343" /></a></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>For the Add New Todo UI we would use: <a title="Tab" href="http://docs.oracle.com/javafx/2/api/javafx/scene/control/Tab.html" target="_blank">Tab</a>, <a title="TabPane" href="http://docs.oracle.com/javafx/2/api/javafx/scene/control/TabPane.html" target="_blank">TabPane</a>, <a title="TextField" href="http://docs.oracle.com/javafx/2/api/javafx/scene/control/TextField.html" target="_blank">TextField</a> and <a title="Button" href="http://docs.oracle.com/javafx/2/api/javafx/scene/control/Button.html" target="_blank">Button</a>.</p>
<h4>Creating and adding to a Tab:</h4>
<p>The components in the Tab for adding a new Todo are:</p>
<p><strong>Field for adding the task name/title</strong>:</p>
<pre class="brush: java; title: ; notranslate">
TextField tNameField = TextFieldBuilder.create()
  .build();
final StringProperty todoTitle = tNameField.textProperty();
</pre>
<p style="text-align: justify">We use properties to bind the values on the components, with binding the value/text in the component is automatically reflected in the property to which it is bound to. In this case the text of the TextField(tNameField) is bound to the a SringProperty called todoTitle. Read <a title="Binding Tutorial " href="http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm" target="_blank">this</a> if you want to get familiar with properties.</p>
<p><strong>Button for saving the todo</strong>:</p>
<pre class="brush: java; title: ; notranslate">
Button addNewButton = ButtonBuilder.create()
  .text(&quot;Add&quot;)
  .onAction(new EventHandler() {
    @Override
    public void handle(ActionEvent actionEvent) {
      Todo todo = new Todo(todoTitle.get());
      todoTitle.set(&quot;&quot;);
      try {
        TodoDAO.saveTodo(todo);
        labelMsg.set(&quot;Successfully added the task&quot;);
        labelVisibility.set(true);
      } catch (UnknownHostException ex) {
        ex.printStackTrace();
      }
    }
  }
)
.build();
</pre>
<p style="text-align: justify">Interesting to see here is the use of <a href="https://www.google.co.in/search?q=builder+pattern" target="_blank">Builder Pattern</a> for creating the components, this gives a great flexibility in terms of chaining the calls on the same instance. We also added the action for the button, obvious action is to save the Todo. People familiar with Swing applications would be aware of adding action listeners by creating an anonymous inner class. In JavaFX components we create an instance of <a title="EventHandler" href="http://docs.oracle.com/javafx/2/api/javafx/event/EventHandler.html" target="_blank">EventHandler</a> and override <a title="EventHandler" href="http://docs.oracle.com/javafx/2/api/javafx/event/EventHandler.html#handle(T)" target="_blank">EventHandler#handle(ActionEvent)</a> method. With Java 8, these can be replaced by using Lambda expressions/closures.</p>
<p style="text-align: justify">The components created above should be added to the Tab, and we make use of <a title="GridPane" href="http://docs.oracle.com/javafx/2/api/javafx/scene/layout/GridPane.html" target="_blank">GridPane</a> to align these components. GridPane is a layout component which allows placing of components into different grids. Aligning the components in GridPane we have,</p>
<pre class="brush: java; title: ; notranslate">
GridPane addNewPane = GridPaneBuilder.create()
  .hgap(5)
  .vgap(5)
  .build();

addNewPane.add(msgLabel,1,2,2,1);
addNewPane.add(tNameLabel,1,3);
addNewPane.add(tNameField,2,3);
addNewPane.add(addNewButton,2,5);

Tab addNewTab = TabBuilder.create()
  .content(addNewPane)
  .text(&quot;Add Task&quot;)
  .closable(false)
  .build();
</pre>
<p>Looks like we have completed building the Add New task UI. Let me put together all these creation code:</p>
<pre class="brush: java; title: ; notranslate">
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.ImageViewBuilder;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import net.javabeat.db.Todo;
import net.javabeat.db.TodoDAO;

import java.net.UnknownHostException;
import java.util.List;
import java.util.Set;

public class TodoAppRunner extends Application{

  public static final int APP_WIDTH = 200;
  public static final int APP_HEIGHT = 300;

  public static void main(String[] args)
    throws UnknownHostException{
    Application.launch(args);
  }

  @Override
  public void start(Stage stage) throws Exception {
    BorderPane root = new BorderPane();
    Scene scene = new Scene(root, APP_WIDTH,APP_HEIGHT);
    Tab addNewTab = buildAddNewTodoUi();
    TabPane tabPane = TabPaneBuilder.create()
      .tabs(addNewTab)
      .build();

    root.setCenter(tabPane);
    stage.setScene(scene);
    stage.setTitle(&quot;My Todo's!&quot;);
    stage.show();
  }

  private Tab buildAddNewTodoUi(){
    Label msgLabel = LabelBuilder.create()
      .text(&quot;&quot;)
      .visible(false)
      .build();

    TextField tNameField = new TextField();

    final StringProperty todoTitle = tNameField.textProperty();
    final StringProperty labelMsg = msgLabel.textProperty();
    final BooleanProperty lblVisibility = msgLabel.visibleProperty();

    Label tNameLabel = new Label(&quot;Task&quot;);
    Button addNewButton = ButtonBuilder.create()
      .text(&quot;Add&quot;)
      .onAction(new EventHandler() {
        @Override
        public void handle(ActionEvent actionEvent) {
          Todo todo = new Todo(todoTitle.get());
          try {
            TodoDAO.saveTodo(todo);
            labelMsg.set(&quot;Successfully added the task&quot;);
            lblVisibility.set(true);
            todoTitle.set(&quot;&quot;);
          } catch (UnknownHostException ex) {
            ex.printStackTrace();
          }
        }
      })
      .build();
    GridPane addNewPane = GridPaneBuilder.create()
      .hgap(5)
      .vgap(5)
      .build();

    addNewPane.add(msgLabel,1,2,2,1);
    addNewPane.add(tNameLabel,1,3);
    addNewPane.add(tNameField,2,3);
    addNewPane.add(addNewButton,2,5);

    Tab addNewTab = TabBuilder.create()
      .content(addNewPane)
      .text(&quot;Add Task&quot;)
      .closable(false)
      .build();

    return addNewTab;

  }
}
</pre>
<p>The source code can be downloaded from <a title="TodoFX" href="https://github.com/sanaulla123/TodoFX" target="_blank">here</a>.</p>
<p>In my <a href="http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-3/" title="Developing a Simple Todo Application using JavaFX, Java and MongoDB- Part-3">next post</a>, I will show how to create a UI for listing all the unfinished Todos, and set the Todos as completed from the UI.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-2/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Developing a Simple Todo Application using JavaFX, Java and MongoDB- Part-1</title>
		<link>http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-1/</link>
		<comments>http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-1/#comments</comments>
		<pubDate>Wed, 09 May 2012 18:27:42 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java FX]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaFX]]></category>
		<category><![CDATA[MongoDB]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3631</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Over a series of 2 posts or so, I would try and show how to develop a simple Todo Desktop application using JavaFX as the Frontend, and the well known NoSQL database MongoDB as the Backend and using Java as the glue between both of them. The main aim of developing this application is to [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Over a series of 2 posts or so, I would try and show how to develop a simple Todo Desktop application using JavaFX as the Frontend, and the well known NoSQL database <a title="MongoDB" href="http://www.mongodb.org/" target="_blank">MongoDB</a> as the Backend and using Java as the glue between both of them. The main aim of developing this application is to understand how we can use MongoDB and its Java driver to communicate with Java applications.</p>
<p>A brief about <a title="MongodDB" href="http://www.mongodb.org/" target="_blank">MongoDB</a>: It is a document oriented <a title="NoSQL" href="http://nosql-database.org/" target="_blank">NoSQL</a> database, which stores the data in the form of <a title="What is JavaScript Object Notation (JSON)?" href="http://www.javabeat.net/2012/04/what-is-javascript-object-notation-json/" target="_blank">JSON</a>-like document structure. I can go one and write more, but we can explore as we go along.</p>
<p>In this post, I would cover:</p>
<ul>
<li>Installing MongoDB</li>
<li>Trying out MongoDB using the command line.</li>
<li>Downloading the Java driver for MongoDB</li>
<li>Developing the backend for our application.</li>
</ul>
<h3><strong>Installing MongoDB</strong></h3>
<p>Download the required MongoDB package from their download <a title="MongoDB Download" href="http://www.mongodb.org/downloads" target="_blank">site</a>.</p>
<p>Unzip the contents into a directory and lets name it as MONGO_HOME. Update the PATH variable to add the MONGO_HOME/bin. This is useful if you want to run mongo, mongod and other command from any location in your command line.</p>
<p>On your command prompt try $: mongod -version and it should print the version of MongoDB you are using.</p>
<h3><strong>Trying out MongoDB using the command line</strong></h3>
<p>You have to create a \data\db directory in your C: if you are using Windows or a /data/db directory on Unix, which mongo would use for storing the data.</p>
<p>Start the mongodb database server by running:</p>
<pre class="brush: bash; title: ; notranslate">
C:\Users\sanaulla&gt;mongod
mongod --help for help and startup options
Wed May 09 22:28:11 [initandlisten]
MongoDB starting : pid=4992 port=27017 dbpath=/data/db/ 32-bit

[initandlisten] db version v1.8.1, pdfile version 4.5
[initandlisten] waiting for connections on port 27017
[websvr] web admin interface listening on port 28017
</pre>
<p>Lets connect to this database using the mogndb client.</p>
<pre class="brush: bash; title: ; notranslate">
C:\Users\sanaulla&gt;mongo
MongoDB shell version: 1.8.1
connecting to: test
</pre>
<p>We try out a few simple commands, you can find</p>
<pre class="brush: bash; title: ; notranslate">
&gt; use test
switched to db test
&gt; show collections
&gt; book = {&quot;name&quot;:&quot;Book1&quot;, &quot;publisher&quot;:&quot;publisher1&quot;}
{ &quot;name&quot; : &quot;Book1&quot;, &quot;publisher&quot; : &quot;publisher1&quot; }
&gt; db.books.save(book)
&gt; db.books.find()
{ &quot;_id&quot; : ObjectId(&quot;4faaa578f65827304120d54b&quot;),
  &quot;name&quot; : &quot;Book1&quot;,
  &quot;publisher&quot; : &quot;publisher1&quot;
}
</pre>
<ul>
<li><strong>use</strong> command is used to switch the database whose name is provided after the <strong>use</strong>. If the db doesn&#8217;t exist a new one is created.</li>
<li><strong>show collections</strong> shows the collections created in the db. A collection can be considered equivalent to a table in RDBMS, but with a flexible schema.</li>
<li><strong>book = {}</strong> creates a JSON object which represents a JSON like document and is equivalent to a row in the RDBMS table. And the attributes within the JSON object represent the columns of an RDBMS table.</li>
<li><strong>db.books.save(book)</strong> saves the given JSON object into the collection name which is &#8220;books&#8221; in this case.</li>
<li><strong>db.books.find()</strong> is used to get all the JSON Objects/rows in the given collections, something similar to SELECT * FROM table_name in SQL.</li>
</ul>
<h3><strong>Downloading the Java driver for MongoDB</strong></h3>
<p>Download the Java driver for MongoDB from their <a title="Java Language Center" href="http://www.mongodb.org/display/DOCS/Java+Language+Center" target="_blank">Java Language Center</a> page, its a jar which has to be added to your applications classpath.</p>
<p>There are a few basics explained <a title="Basics" href="http://www.mongodb.org/display/DOCS/Java+Tutorial" target="_blank">here</a> to get you started with the Java Driver. Dont worry, I will go through few of those as we develop the application further.</p>
<h3><strong>Developing the backend for our application</strong></h3>
<p>Ah, finally! Lets start with building the backend for our Todo application, lets call it TodoFX and also test the backend via the command line.</p>
<p>Starting with the model class for our application, A Todo would have the task name, status i.e whether it is completed or not, date of adding, and date when it was finished.</p>
<pre class="brush: java; title: ; notranslate">
//Todo.java
import java.util.Date;

public class Todo {
  public Todo(String task,
              boolean completed,
              Date added){
    this.task = task;
    this.completed = completed;
    this.added = added;
  }

  public Todo(String task){
    this.task = task;
    this.added = new Date();
    this.completed = false;
  }

  @Override
  public String toString(){
    return added+&quot;: &quot;+this.getTask();
  }

  private String task;
  private boolean completed;
  private Date added;
  private Date finished;

  public String getTask() {
    return task;
  }

  public void setTask(String task) {
    this.task = task;
  }

  public boolean isCompleted() {
    return completed;
  }

  public void setCompleted(boolean completed) {
    this.completed = completed;
  }

  public Date getAdded() {
    return added;
  }

  public Date getFinished() {
    return finished;
  }

  public void setFinished(Date finished) {
    this.finished = finished;
  }
}
</pre>
<p>To start persisting the data, we need a database connection to the MongoDB. The Java Driver provides <a title="Mongo API" href="http://api.mongodb.org/java/current/com/mongodb/Mongo.html" target="_blank">Mongo</a> class which can be used to obtain the database connection. If we use the default constructor then it returns the database connection to the local database. In this example we would do that. I will try to see if I can connect to a cloud database and show the same.</p>
<pre class="brush: java; title: ; notranslate">
Mongo mongo = new Mongo();
</pre>
<p>and then use <a title="Monog#getDB()" href="http://api.mongodb.org/java/current/com/mongodb/Mongo.html#getDB(java.lang.String)" target="_blank">Mongo#getDB(dbName)</a> to return the database where we would like to store our collections and objects. The database object is of type <a title="Mongo DB" href="http://api.mongodb.org/java/current/com/mongodb/DB.html" target="_blank">DB</a>.</p>
<pre class="brush: java; title: ; notranslate">
DB db = mongo.getDB(name);
</pre>
<p>I extracted these into a different class called DbManager</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
//DbManager.java
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import java.net.UnknownHostException;

public class DbManager {

  private static DB db;
  public static DB getDb (String name)
    throws UnknownHostException {
    Mongo mongo = new Mongo();
    if ( db == null){
      db = mongo.getDB(name);
    }
    return db;
  }
}
</pre>
<p>Ok, so its time to see how we can <strong>SAVE</strong> and <strong>FIND</strong> all the todos added. Before that, our database name is: &#8220;<strong>todoapp</strong>&#8221; and the collection name is: &#8220;<strong>todo</strong>&#8221;</p>
<p><strong>Saving the Todo instance to the database</strong>:</p>
<p>Create a <a title="DBObject" href="http://api.mongodb.org/java/current/com/mongodb/DBObject.html" target="_blank">DBObject</a> from the data present in the Todo instance. I prefer to use the <a title="BasicDBObjectBuilder" href="http://api.mongodb.org/java/current/com/mongodb/BasicDBObjectBuilder.html" target="_blank">BasicDBObjectBuilder</a> to create an instance of DBObject.</p>
<pre class="brush: java; title: ; notranslate">
DBObject dbObject = BasicDBObjectBuilder.start()
                   .add(&quot;task&quot;,todo.getTask())
                   .add(&quot;completed&quot;,todo.isCompleted())
                   .add(&quot;added&quot;,todo.getAdded())
                   .get();
</pre>
<p>the <a href="http://api.mongodb.org/java/current/com/mongodb/BasicDBObjectBuilder.html#add(java.lang.String, java.lang.Object)" target="_blank">BasicDBObjectBuilder#add()</a>, takes in a key, value pair where the key represents the column name and the value represents the item in the column. The advantage with NoSQL is that there is no requirement of a rigid schema. I could have one row with 3 keys, another row with 4 keys and so on.</p>
<p>After creating the DBObject, it has to be added to the collection and then persisted to the database.</p>
<pre class="brush: java; title: ; notranslate">
DB db = DbManager.getDb(&quot;todoapp&quot;);
DBCollection dbCollection = db.getCollection(&quot;todo&quot;);
dbCollection.save(dbObject);
</pre>
<p>Pretty straight forward right? And here you are done with persisting your data to the database. How simple can this get? I just removed the fear of PreparedStatments, Connections, SQLExceptions and what not.<br />
Note: In all the cases the DbManager is the class which we have created somewhere near the starting of this example.</p>
<p><strong>Retrieving all the Todos from the database</strong>:</p>
<p>- Get the database and fetch the collection from it.<br />
- Iterate through the collection and get each of the values for the available keys(or columns)<br />
- Create instance of Todo from these retrieved values.</p>
<p>Let me show the code:</p>
<pre class="brush: java; title: ; notranslate">
DB db = DbManager.getDb(DBNAME);
DBCollection dbCollection = db.getCollection(COLLECTION_NAME);
DBCursor dbCursor = dbCollection.find();
List allTodos = new ArrayList();
while ( dbCursor.hasNext()){
  DBObject dbObject = dbCursor.next();
  String task = String.valueOf(dbObject.get(&quot;task&quot;));
  Date added = (Date)dbObject.get(&quot;added&quot;);
  boolean completed = (Boolean)dbObject.get(&quot;completed&quot;);
  Todo todo = new Todo(task,completed, added);
  allTodos.add(todo);
}
return allTodos;
</pre>
<p>One new thing is the use of <a title="DBCursor" href="http://api.mongodb.org/java/current/com/mongodb/DBCursor.html" target="_blank">DBCursor</a>, which is an iterator over the database results (think ResultSet).</p>
<p>Let me call this class which provides save() and find() as TodoDAO</p>
<pre class="brush: java; title: ; notranslate">
//TodoDAO.java
import com.mongodb.*;
import java.net.UnknownHostException;
import java.util.*;

public class TodoDAO {

  private static final String DBNAME = &quot;todoapp&quot;;
  private static final String COLLECTION_NAME = &quot;todo&quot;;
  public static void saveTodo(Todo todo)
    throws UnknownHostException{
    DBObject dbObject = BasicDBObjectBuilder.start()
      .add(&quot;task&quot;,todo.getTask())
      .add(&quot;completed&quot;,todo.isCompleted())
      .add(&quot;added&quot;,todo.getAdded())
      .get();
    DB db = DbManager.getDb(DBNAME);
    DBCollection dbCollection = db.getCollection(COLLECTION_NAME);
    dbCollection.save(dbObject);
  }

  public static List getAllTodos()
    throws UnknownHostException{
    DB db = DbManager.getDb(DBNAME);
    DBCollection dbCollection = db.getCollection(COLLECTION_NAME);
    DBCursor dbCursor = dbCollection.find();
    List allTodos = new ArrayList();

    while ( dbCursor.hasNext()){
      DBObject dbObject = dbCursor.next();
      String task = String.valueOf(dbObject.get(&quot;task&quot;));
      Date added = (Date)dbObject.get(&quot;added&quot;);
      boolean completed = (Boolean)dbObject.get(&quot;completed&quot;);
      Todo todo = new Todo(task,completed, added);
      allTodos.add(todo);
    }

    return allTodos;
  }
}
</pre>
<p>I think with this we have pretty much the required backend to build further. There are lot of aspects of query, like providing the WHERE clauses, then we can do indexing. I havent explored all those, and I would surely write about it as and when I explore.</p>
<p>Let me try and run this via command line:</p>
<pre class="brush: java; title: ; notranslate">
//TodoAppRunner.java
public class TodoAppRunner{
  public static void main(String[] args)
    throws UnknownHostException{
    Todo todo = new Todo(&quot;Task 1 from Command Line&quot;);
    TodoDAO.saveTodo(todo);

    todo = new Todo(&quot;Task 2 from Command Line&quot;);
    TodoDAO.saveTodo(todo);

    todo = new Todo(&quot;Task 3 from Command Line&quot;);
    TodoDAO.saveTodo(todo);

    List allTodos = TodoDAO.getAllTodos();
    for ( Todo aTodo : allTodos){
      System.out.println(aTodo);
    }
  }
}
</pre>
<p>Output:</p>
<pre class="brush: bash; title: ; notranslate">
Wed May 09 23:42:07 IST 2012: Task 1 from Command Line
Wed May 09 23:42:09 IST 2012: Task 2 from Command Line
Wed May 09 23:42:09 IST 2012: Task 3 from Command Line
</pre>
<p>I have used <a title="IntelliJ Idea" href="http://www.jetbrains.com/idea/" target="_blank">IntelliJ Idea </a> IDE for this sample application.</p>
<p><strong>Next</strong>: <a title="Developing a Simple Todo Application using JavaFX, Java and MongoDB- Part-2" href="http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-2/">Building the Add New Todo UI using JavaFX</a>.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/developing-a-simple-todo-application-using-javafx-java-and-mongodb-part-1/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Using JavaFX Chart API to add charts to Swing applications</title>
		<link>http://www.javabeat.net/2012/05/using-javafx-chart-api-to-add-charts-to-swing-applications/</link>
		<comments>http://www.javabeat.net/2012/05/using-javafx-chart-api-to-add-charts-to-swing-applications/#comments</comments>
		<pubDate>Sun, 06 May 2012 19:10:52 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java FX]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaFX]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3607</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In our previous post we looked at how we can embed JavaFX components into Swing applications. As Java Swing lacks Charting API, we can make use of the JavaFX Chart API and not depend on other 3rd party libraries like JFreeChart and others. The javafx.scene.chart is the package which contains all the charting related classes. [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p style="text-align: justify">In our <a title="Embedding HTML into Java Swing Applications" href="http://www.javabeat.net/2012/05/embedding-html-into-java-swing-applications/">previous</a> post we looked at how we can embed JavaFX components into Swing applications. As Java Swing lacks Charting API, we can make use of the JavaFX Chart API and not depend on other 3rd party libraries like JFreeChart and others. The <a title="JavaFX Chart Package" href="http://docs.oracle.com/javafx/2/api/javafx/scene/chart/package-summary.html" target="_blank">javafx.scene.chart</a> is the package which contains all the charting related classes. In this example we will look at creating Scatter Charts and Bar Charts which are categorized as XYCharts which is nothing but these charts are plotted on a X and Y axis. The classes for the charts to be used are <a title="ScatterChart" href="http://docs.oracle.com/javafx/2/api/javafx/scene/chart/ScatterChart.html" target="_blank">javafx.scene.chart.ScatterChart</a> and <a title="BarChart" href="http://docs.oracle.com/javafx/2/api/javafx/scene/chart/BarChart.html" target="_blank">javafx.scene.chart.BarChart</a>. If you happen to look at the declaration of these classes, they accept generic types &lt;X,Y&gt; where X indicates the type on the X Axis and Y indicates the type on the Y axis. These charts require a set of axis to be defined before they are used. If the axis is of type Number, then one can use <a title="NumberAxis" href="http://docs.oracle.com/javafx/2/api/javafx/scene/chart/NumberAxis.html" target="_blank">NumberAxis</a> and for String values one can make use of <a title="CategoryAxis" href="http://docs.oracle.com/javafx/2/api/javafx/scene/chart/CategoryAxis.html" target="_blank">CategoryAxis</a>. For each of the Number axis or category axis we can define the range of of values to be plotted on the axis. Let me show some code on how it can be achieved:</p>
<pre class="brush: java; title: ; notranslate">
NumberAxis yAxis =
    new NumberAxis(0.0,5.0,1.0);
NumberAxis xAxis =
    new NumberAxis(0.0,5.0,1.0);
//Scatter chart with 2 axis defined. Both are number axis
ScatterChart scatterChart =
    new ScatterChart&lt;&gt;(xAxis,yAxis);
</pre>
<p>For a Chart with a Category and Number axis, we can have something like:</p>
<pre class="brush: java; title: ; notranslate">
NumberAxis lineYAxis =
    new NumberAxis(0,100_000,10_000);
CategoryAxis lineXAxis =
    new CategoryAxis();
//One can set the label for axis as well.
lineYAxis.setLabel(&quot;Sales&quot;);
lineXAxis.setLabel(&quot;Products&quot;);

// A bar chart with X and Y axis representing
// string and numbers.
BarChart barChart =
    new BarChart&lt;&gt;(lineXAxis,lineYAxis);
</pre>
<p>Moving ahead, our next task is to add some data to these charts. As you already have seen, the scatter chart accepts &lt;Number,Number&gt; data while the bar chart accepts &lt;String,Number&gt; data. The charts being demonstrated in our example here are XY charts which means that they are plotted against X Axis and Y Axis, so  we use <a title="XYChart" href="http://docs.oracle.com/javafx/2/api/javafx/scene/chart/XYChart.html" target="_blank">XYChart</a> at all places. Lets populate some data to our scatter chart</p>
<pre class="brush: java; title: ; notranslate">
XYChart.Series series = new XYChart.Series&lt;&gt;();
series.setName(&quot;Value 1&quot;);
series.getData().add(getData(1.2,3.4));
series.getData().add(getData(3.4,4.5));
series.getData().add(getData(1.5,1.2));
series.getData().add(getData(4.5, 1.6));
</pre>
<p>where our function getData is defined as</p>
<pre class="brush: java; title: ; notranslate">
private XYChart.Data getData(double x, double y){
  XYChart.Data data = new XYChart.Data&lt;&gt;();
  data.setXValue(x);
  data.setYValue(y);
  return data;
}
</pre>
<p>To populate the data for bar chart we write something like:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
// First Series
XYChart.Series bar1 = new XYChart.Series&lt;&gt;();
bar1.setName(&quot;Computing Devices&quot;);
bar1.getData().add(getData(40000,&quot;Desktop&quot;));
bar1.getData().add(getData(30_000,&quot;Netbooks&quot;));
bar1.getData().add(getData(70_000,&quot;Tablets&quot;));
bar1.getData().add(getData(90_000,&quot;Smartphones&quot;));

//Second series
XYChart.Series bar2 = new XYChart.Series&lt;&gt;();
bar2.setName(&quot;Consumer Goods&quot;);
bar2.getData().add(getData(60_000,&quot;Washing Machines&quot;));
bar2.getData().add(getData(70_000,&quot;Telivision&quot;));
bar2.getData().add(getData(50_000,&quot;Microwave Ovens&quot;));

// Add both the series to the bar chart
// Notice the use of addAll() method here
// and only add() for scatter chart
barChart.getData().addAll(bar1,bar2);
</pre>
<p>Once the program is working, the above 2 graphs would be represented as:</p>

<a href='http://www.javabeat.net/2012/05/using-javafx-chart-api-to-add-charts-to-swing-applications/barchart/' title='Barchart'><img width="150" height="150" src="http://www.javabeat.net/wp-content/uploads/2012/05/Barchart-150x150.png" class="attachment-thumbnail" alt="Barchart" /></a>
<a href='http://www.javabeat.net/2012/05/using-javafx-chart-api-to-add-charts-to-swing-applications/scatter/' title='scatter'><img width="150" height="150" src="http://www.javabeat.net/wp-content/uploads/2012/05/scatter-150x150.png" class="attachment-thumbnail" alt="scatter" /></a>
<a href='http://www.javabeat.net/2012/05/using-javafx-chart-api-to-add-charts-to-swing-applications/chartdeom/' title='ChartDemo'><img width="150" height="150" src="http://www.javabeat.net/wp-content/uploads/2012/05/ChartDeom-150x150.png" class="attachment-thumbnail" alt="ChartDemo" /></a>

<p>Now that we have touched upon the basics of adding chart, the other things which are to be taken care are the layout of the JavaFX components and then adding the JFXPanel into a JFrame. If you dont know what a JFXPanel is please read this post for some information on the same.</p>
<p>The complete code for this sample is:</p>
<pre class="brush: java; title: ; notranslate">
import javafx.application.Platform;
import javafx.beans.property.SimpleListProperty;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.chart.*;
import javafx.scene.layout.GridPane;

import javax.swing.*;
import java.awt.*;

public class JavaChartDemo {

  public static void main ( String[] args){
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        ChartFrame mainFrame = new ChartFrame();
        mainFrame.setVisible(true);
        }
      });
    }
  }

class ChartFrame extends JFrame {

  JFXPanel fxPanel;
  public ChartFrame(){
    initSwingComponents();

    initFxComponents();
  }

  private void initSwingComponents(){
    JPanel mainPanel = new JPanel(new BorderLayout());
    fxPanel = new JFXPanel();
    mainPanel.add(fxPanel, BorderLayout.CENTER);

    JLabel titleLabel = new JLabel(&quot;Charts in Swing applications&quot;);
    mainPanel.add(titleLabel, BorderLayout.NORTH);

    this.add(mainPanel);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(800,400);
  }

  private void initFxComponents(){

    Platform.runLater(new Runnable() {
      @Override
      public void run() {
          GridPane grid = new GridPane();
          Scene scene = new Scene(grid, 800, 400);

          /**
           * Construct and populate Scatter chart
           */
          NumberAxis yAxis = new NumberAxis(0.0,5.0,1.0);
          NumberAxis xAxis = new NumberAxis(0.0,5.0,1.0);
          ScatterChart scatterChart =
            new ScatterChart&lt;&gt;(xAxis,yAxis);
          XYChart.Series series =
            new XYChart.Series&lt;&gt;();
          series.setName(&quot;Value 1&quot;);
          series.getData().add(getData(1.2,3.4));
          series.getData().add(getData(3.4,4.5));
          series.getData().add(getData(1.5,1.2));
          series.getData().add(getData(4.5, 1.6));
          scatterChart.getData().addAll(series);
          grid.add(scatterChart,0,0);

          /**
           * Construct and populate Bar chart.
           * It uses 2 series of data.
           */
          NumberAxis lineYAxis =
            new NumberAxis(0,100_000,10_000);
          lineYAxis.setLabel(&quot;Sales&quot;);
          CategoryAxis lineXAxis = new CategoryAxis();
          lineXAxis.setLabel(&quot;Products&quot;);
          BarChart barChart =
            new BarChart&lt;&gt;(lineXAxis,lineYAxis);
          XYChart.Series bar1 =
            new XYChart.Series&lt;&gt;();
          bar1.setName(&quot;Computing Devices&quot;);
          bar1.getData().add(getData(40000,&quot;Desktop&quot;));
          bar1.getData().add(getData(30_000,&quot;Netbooks&quot;));
          bar1.getData().add(getData(70_000,&quot;Tablets&quot;));
          bar1.getData().add(getData(90_000,&quot;Smartphones&quot;));

          XYChart.Series bar2 = new XYChart.Series&lt;&gt;();
          bar2.setName(&quot;Consumer Goods&quot;);
          bar2.getData().add(getData(60_000,&quot;Washing Machines&quot;));
          bar2.getData().add(getData(70_000,&quot;Telivision&quot;));
          bar2.getData().add(getData(50_000,&quot;Microwave Ovens&quot;));

          barChart.getData().addAll(bar1,bar2);
          grid.setVgap(20);
          grid.setHgap(20);
          grid.add(barChart,2,0);
          fxPanel.setScene(scene);
        }
      });

  }

  private XYChart.Data getData(double x, double y){
    XYChart.Data data = new XYChart.Data&lt;&gt;();
    data.setXValue(x);
    data.setYValue(y);
    return data;
  }

  private XYChart.Data getData(double x, String y){
    XYChart.Data data = new XYChart.Data&lt;&gt;();
    data.setYValue(x);
    data.setXValue(y);
    return data;
  }
}

</pre>
<p style="text-align: center"><a href="http://www.javabeat.net/wp-content/uploads/2012/05/ChartDeom.png"><img class="aligncenter  wp-image-3616" src="http://www.javabeat.net/wp-content/uploads/2012/05/ChartDeom-300x191.png" alt="" width="500" height="191" /></a></p>
<p>We will try to update and posts JavaFX chart specific examples. Please do subscribe to the posts to keep a track of the new updates.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/using-javafx-chart-api-to-add-charts-to-swing-applications/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
