06
Jul
09

JavaFX – ClipView [ Scroll + Pane ]

JavaFX has new layout – ClipView – which can be used to implement scroll or pannable view.

We can set a node to ClipView which needs to be clipped and shown. The clip area can be controlled by specifying attributes – clipX and clipY. ClipView can also handle panning using mouse, which can enabled using pannable attribute.

For Applet mode, click on above image

For standalone mode

In above sample a large image is added to ImageView, which in-turn is added to ClipView. The clipX and clipY attributes are bound to horizontal and vertical ScrollBars. The clip rectangle can be updated by moving the scrollbars.


var scrollClipView : ClipView = ClipView {
    clipX: bind hScroll.value
    clipY: bind vScroll.value
    node: imageView
    pannable: false
    layoutInfo: LayoutInfo {
        width: 300
        height: 200
    }
}

The second ImageView is again added to ClipView. This time clipX and clipY are not bound to scrollbars. Instead the pannable attribute is set to true. User can move the image using mouse.

Try it out and let me know feedback!

Source:

06
Jul
09

JavaFX – System Monitor

My previous post on LineChart uses simulated CPU usage data. Just thought of updating that to show live CPU and Memory information.

A tribute to all    users

For Applet mode, click on above image

For standalone mode

One of the way to implement this is to use some existing command line utilities. I used – top – command to get the CPU and Memory usage information. Execute top using ProcessBuilder, get the Process instance. Get the output stream from process and read the output of top command. Now parse this content (a bit tricky, each version had its own output format) to get the information.

Note: The implementation is not concrete (as it relies on simple text parsing), may not work on some platforms or locales due to difference in output of top command. It will not work on platforms which does not support top command.

Try it out and let me know feedback

Source:

06
Jul
09

JavaFX – LineChart

JavaFX 1.2 introduces new Chart APIs. Here we discuss about how to plot line chart using LineChart API.

For creating a chart, we need to create following instance

Note: Pie chart is an exception. In this case we don’t need to create instance of Series. Series is required only for X-Y chart types.

Lets implement a Line-Chart which updates its data dynamically. In this case a CPU monitor is simulated by generating random data from java class. The data is generated in a java Thread. The data is sent to JavaFX using a listener interface so as to update the chart. The notification is done via Event Dispatch Thread.

Update: Sample using live CPU and Memory information is available here.

For Applet mode, click on above image

For standalone mode

Create an instance of Series to plot chart for CPU usage of user, system and idle:


    var cpuLineChartSeries : LineChart.Series[] [
        LineChart.Series name: "User" },
        LineChart.Series name: "System" },
        LineChart.Series name: "Idle" }
    ];

Create an instance of Chart and associate the Series with this chart:


    var cpuLineChart = LineChart {
        
        title: "CPU Monitor"
        legendSide: Side.TOP
        showSymbols: false
        
        data: cpuLineChartSeries
        
        xAxis: NumberAxis {
            lowerBound: 1
            upperBound: 10
            tickUnit: 1
            label: "Minitues"
            tickMarkLength: 10
        }

        yAxis: NumberAxis {
            lowerBound: 0
            upperBound: 100
            tickUnit: 20
            label: "CPU %"
            tickMarkVisible: false
        }
        
        height: height
        width: width
    }

A simple UpdateListener interface is created. Which will be used to update data from java to javafx. Dummy CPU data is generated by CPUData class. The update is performed via Event Dispatch Thread using SwingUtilities.invokeLater( <Runnable> ).


    /**
     * Update listeners via Event Dispatch Thread
     */
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            updateListener.updateCPU(user, sys, idle);
        }
    });

This update notification is handled in the JavaFX class and we can insert the data in chart as shown below.


    public override function updateCPU(user : Integer, sys : Integer, idle : Integer) {
        
        insert LineChart.Data 
            xValue: cpuIndex
            yValue: user
        into cpuLineChartSeries[0].data;

        insert LineChart.Data {
            xValue: cpuIndex
            yValue: sys
        into cpuLineChartSeries[1].data;

        insert LineChart.Data {
            xValue: cpuIndex
            yValue: idle
        into cpuLineChartSeries[2].data;

        cpuIndex += 1;
    }

When the index reaches the upper-bound, we can adjust the lowerBound and upperBound attributes of X-Axis, so as to shift the chart towards left. Also we may remove the initial chart data which are not visible.

Update:

As noted in comments section below, there is some Memory-Leak when we try to continuously update the bounds. Updation of bounds triggers updation of ticks and Skin related code of Label. For now instead of NumberAxis I have used a custom NoTickNumberAxis which supress the tick updates.


class NoTickNumberAxis extends NumberAxis {
    override function updateTickMarks() : Void {

    }
}

Try it out and let me know feedback!

Source:

19
Jun
09

JavaFX – RSS and ATOM Task

JavaFX 1.2 provides new APIs to handle RSS and ATOM feeds. RssTask and AtomTask parses the feeds and provide the content as JavaFX objects. It can also be configured to provide updates on regular intervals.

RssTask parses the feed and provides the content as Channel and Item objects. These objects in-turn provides other information such as image, link, title, category, date etc.

Similarly AtomTask parses feed and provides Feed and Entry objects. These objects in-turn provides information such as author, category, link, logo, contributors etc.

News ticker using Yahoo RSS feed is given below.

For Applet mode, click on above image

For standalone mode

RssTask Usage:


var rssTask = RssTask {
    
    location: "http://rss.news.yahoo.com/rss/world"
    interval: 300s

    onException: function(e) {
        e.printStackTrace();
    }

    onChannel: function(channel) {
        println("{channel.title}");
    }

    onItem: function(item) {
        println("{item.title}");
    }
}
rssTask.start();

AtomTask Usage:


var atomTask = AtomTask {
    
    location: "http://jfxstudio.wordpress.com/feed/atom"
    interval: 300s

    onException: function(e) {
        e.printStackTrace();
    }

    onFeed: function(feed) {
        println("{feed.title}");
    }

    onEntry: function(entry) {
        println("{entry.title}");        
    }
}
atomTask.start();

Source:

18
Jun
09

JavaFX – Upload and Download Large Files

We can upload or download large files using new HttpRequest attributes available in JavaFX 1.2.

HttpRequest has input and onInput attributes that provides InputStream which can be used to download data. This stream supports mark, reset, available, skip etc. But to support this HttpRequest buffers the data. Due to this buffering it was not possible to use this approach to download large files.

JavaFX 1.2 introduce two new attributes – source (InputStream) and sink (OutputStream). If we set sink attribute, we can directly download the content of stream without buffering. Also with source we can upload the content. Eg: By setting it to FileInputStream. When source or sink attribute is used, corresponding input, onInput, output, onOutput will not be functional.

For Applet mode, click on above image

For standalone mode

The application downloads a larger version of the photo. I took it from Somnathpur using Nikon Coolpix! :)


function downloadFile(url , outputFile) {

    def getRequest: HttpRequest = HttpRequest {

        location: url
        sink: new java.io.FileOutputStream(outputFile)

        onToRead: function(bytes: Long) {
            toRead = bytes;
            println("onToRead({bytes})");
        }

        onRead: function(bytes: Long) {
            read = bytes;
            println("onRead - {read * 100/toRead}%");
        }

        onDone: function() { println("onDone") }
    }

    getRequest.start();
}

In above sample, sink is assigned to a FileOutputStream. So all the content will be directly written to file without buffering. Note: For making the application compatible with mobile or other platforms we will have to use only subset of java.io package. Example: MID Profile Core API.

Source:

12
Jun
09

JavaFX – Color Picker

Simple JavaFX Color-Picker control. I have provided similar controls before as part of blog and sample but this one can be easily incorporated into other products.

For Applet mode, click on above image

For standalone mode

The control can be instantiated and added just like any other node using layout or translate.
Try it out and let me know feedback.

Coming up next – Date-Picker!

Source:

11
Jun
09

JavaFX – Passing Arguments

I received a query on how to pass arguments in JavaFX. It basically depends on how we deploy the application. The application can be deployed using JavaWebStart, as an applet or launched from command line.

Lets take a simple application..


var text = Text {
    x: 10, y: 30
    font : Font size : 16 }
    content: "Argument {FX.getArgument( "key" )}"
}

The argument is passed as key-value pair. The value is retrieved using FX.getArgument( <key> ) method. Arguments can be passed to various deployment modes as shown below.

Command Line:


javafx -cp FXArguments.jar fxarguments.Main key="From Command Line"

Applet:


<script src="http://dl.javafx.com/1.2/dtfx.js"></script>
<script>
    javafx(
        {
              archive: "FXArguments.jar",
              draggable: true,
              width: 250,
              height: 80,
              code: "fxarguments.Main",
              name: "FXArguments",
              key: "from Applet"
        }
    );
</script>

Launch Applet Example

Java Web Start:


<jnlp spec="1.0+" codebase="dist" href="FXArguments.jnlp">
    <application-desc main-class="com.sun.javafx.runtime.main.Main">
        <argument>MainJavaFXScript=fxarguments.Main</argument>
        <argument>key=from Java Web Start</argument>
    </application-desc>
</jnlp>

Launch Web Start Example

Source:

10
Jun
09

JavaFX + Yahoo Placemaker + Maps

I have my travel itinerary or a document with list of cities, such as Seven Wonders of the World. I would like to retrieve the list of cities and the location information associated with it. How to do this??

Yahoo! released new Yahoo! Placemaker APIs. These APIs search for name of places in plain text document and returns the latitude and longitude associated with the place. You can either provide a text or a URL as input to the API. The output can be obtained in XML or RSS format.

Combine above information with Yahoo! Maps will return the maps associated with all places mentioned in specified document! Itn’t that cool?! :)




May be I must write more applications and publish at Java-Store! :)

For Applet mode, click on above image

For standalone mode

In above application we provide a URL which the Placemaker API will parse and returns the list of places. This information is given to Map Image API to retrieve the image. Any valid http URL can be provided as input. There is currently a 50 kbs limit for documents processed by Placemaker. Documents above this length are rejected and returns status 413. Please enter a new URL in textfield and press enter to load new places.

Source:

10
Jun
09

JavaFX – Skinnable Controls

Its long time since I blogged and lot of things happened during that time – Release of JavaFX 1.2, Java Store, New Samples… and lot more to write about! :) Let me start with UI Controls

Following are some of the UI controls – Button, CheckBox, Hyperlink, Label, ListView, ProgressBar, ProgressIndicator, RadioButton, ScrollBar, Slider, TextBox, ToggleButton

The article on Node-Based Controls demonstrates its usage. So let me focus on how to update the skin of these controls.

The skin attribute of Control class allows you to associate a Skin. The Skin is responsible for implementing the user interface using on scene-graph nodes and defining the behavior of the control. The Behavior has the logic for handling key and mouse events.

Sounds complicated? confused? Control, Skin, Behavior.. For now lets look at a simple and straight forward way to just change the color and some basic attributes of Skin.

JavaFX already has a default skin implementation – Caspian. Its in com.sun.javafx.scene.control.caspian package. For each control, there is corresponding skin implementation. We can change few attributes of these skin implementations and customize the look of controls.

Example: To update skin of Button, we can customize the attributes of ButtonSkin implementation.


var button = Button {
    text: "Button"

    skin: ButtonSkin {
        borderFill: Color.BLACK
        focusFill: Color.BLUE
        highlightFill: Color.GREEN
        shadowFill: Color.GRAY
        textFill: Color.RED
        fill: Color.WHITE
    }

}

Similarly a TextBox can be customized as shown below:


var textBox = TextBox {
    text: "TextBox"

    skin: TextBoxSkin {
        backgroundFill: Color.YELLOW
        borderFill: Color.BLACK
        caretFill: Color.BLUE
        focusFill: Color.BEIGE
        highlightFill: Color.BLUE
        promptTextFill: Color.GRAY
        selectedTextFill: Color.WHITE
        shadowFill: Color.DARKGRAY
        textFill: Color.BLACK
    }

}

More attributes and implementation is available in the source.
Try it out and let me know feedback! :)

Source:

06
May
09

JavaFX – Fish Eye Menu

I came across a nice comparison of Fish-Eye-Menu in Flash and Silverlight. Looks Cool! So thought of writing one in JavaFX and compare..

For Applet mode, click on above image

For standalone mode

So how much time did it take to implement it in JavaFX?
Any guess?!

Source: