Monday Jun 08, 2015

From Responsive CSS to Responsive JavaScript with Foundation.js & Knockout.js

Whereas Response.js, discussed in the previous blog entry, is handy for modifying the DOM by swapping out DOM elements (instead of using CSS rules to hide DOM elements) based on screen size, an alternative approach, focused on HTML fragments, is provided by Foundation.js, in particular, Foundation Interchange.

Foundation is a UI framework, comparable to Twitter Bootstrap and Angular UI. In the 5.0 release of Foundation, Interchange was made available. Interchange is responsive JavaScript, allowing you to do powerful stuff on the client side, within the HTML view of your application:

<div data-interchange="
     [fragments/small.html, (small)], 
     [fragments/medium.html, (medium)], 
     [fragments/large.html, (large)]">
</div>

Below, you can see that I have a folder named "fragments", in which I have the HTML files referenced above. The div above is found, in this example, in the "index.html", which you can see is relative to the "fragments" folder. Thanks to the above code, automatically, when the screen size changes, Foundation Interchange loads the appropriate fragment.

For this example, each of the fragments contain content like this, here for the "small.html":

<b>You're using a small resolution.</b>

Just like with Response.js, and unlike CSS rules, nothing is hidden. Instead, files are loaded or not loaded, depending on the size of the screen. In the first screenshot below, you can see in the Network Monitor that the "small.html" is loaded, while none of the other fragments are loaded, simply because the screen size has changed and Foundation Interchange has picked that up and unloaded the fragments that may have been loaded before, while loading the new fragment appropriate to the current screen size:

In the next example, there's a different screen size, and so as you can see Foundation Interchange has now loaded "medium.html", while no other fragments have been loaded and those that were loaded before have been unloaded:

If you were using Google Maps in your application and assuming you didn't want to include that for small devices, you'd simply not have the Google Maps code in the "small.html". That would mean that none of the Google Maps libraries would be loaded for small devices, since for small devices you're loading the "small.html".

How to set up Foundation Interchange? Start by including Foundation in your Bower file, as shown below:

"dependencies": {
    "knockout": "3.3.0",
    "requirejs-text": "2.0.14",
    "requirejs": "2.1.17",
    "bootstrap-dropdown": "*",
    "jquery": "2.1.4",
    "responsejs": "0.9.1",
    "foundation": "5.5.2"
}

Then, in the 'main.js', which is highlighted in the first screenshot in this blog entry, (in this case, I'm referring to Solid Knockout, where all the code in this blog entry is included), add the changes shown in bold below to set up and initialize Foundation:

require.config({
    baseUrl: './',
    paths: {
        knockout: './js/libraries/knockout/dist/knockout',
        text: './js/libraries/requirejs-text/text',
        jquery: './js/libraries/jquery/dist/jquery',
        response: './js/libraries/responsejs/response',
        foundation: './js/libraries/foundation/js/foundation',
        initComponents: './js/initComponents'
    },
    // Shim configuration for modules that do not expose AMD:
    shim : {
        'response':{
            deps: ['jquery']
        },  
        'foundation':{
            deps: ['jquery']
        }
    },
    waitSeconds: 2
});
require(['knockout', 'initComponents', 'response', 'foundation'],
    function (ko, initComponents) {
        $(document).foundation();
        var self = this;
        self.weAreSmall = ko.observable();
        Response.create({
            breakpoints: [0, 480, 481]
        });
        Response.action(function() {
             if (Response.band(0, 480)){
                 self.weAreSmall(true);
             } else {
                 self.weAreSmall(false);
             }
        });
        ko.applyBindings(new initComponents());
    }
);

After you've done the above, use "data-interchange" in a div element, exactly as shown at the start of this blog entry.

As in the previous blog entry, I'm indebted to my colleague JB Brock for the code and explanation above, which you can follow on YouTube here, from about the 24th minute. All the code above is incorporated into Solid Knockout.

Sunday Jun 07, 2015

From Responsive CSS to Responsive JavaScript with Response.js & Knockout.js

More often than not, you use CSS media rules to specify whether something should be displayed based on screen resolution. For example, imagine you have a logo which you'd rather not display on smaller devices because you want that real estate for other things:

@media (min-width: 481px) {
    .logo:before { 
          content:url("images/coca_cola_logo.png"); 
          display: block; 
          text-align:center;
    }
}
@media (max-width: 480px) {
    .logo:before { 
          display: none;
    }  
}

And then you use the logo class as follows: 

<div>
    <a class="logo" href="http://cocacola.com"></a>
</div>

However, when the width of the screen is less than 480, the logo is still loaded, you can see it in the DOM, e.g., in the Browser DOM window in the IDE, though it is not being used—it is simply hidden from the view:

Imagine that you could dynamically swap content based on breakpoints and data attributes. That's what Response.js is all about. For this specific example, with a single logo, setting up a content swapping solution is overkill. But imagine you have heaps of logos and other items that need to be displayed or hidden or resized based on screen size. Also, imagine you're using some heavy JavaScript loading solutions, such as Google Maps, which you'd like to have available for large screen sizes, though not for mobile devices. By default, all those JavaScript libraries and other artifacts would be loaded even though they'd never be used, the Google Maps viewer would simply be hidden from the HTML view whenever you decide to exclude it. That's potentially a massive waste of resources, e.g., battery life, on a small device.

Simply delete your CSS media rules, e.g., the ones shown above. Rewrite the CSS logo class to the following, i.e., now there's no CSS rule, simple a class:

.logo:before { 
       content:url("images/coca_cola_logo.png"); 
       display: block; 
       text-align:center;
}

Then include "responsejs" in your Bower file:

"dependencies": {
  "knockout": "3.3.0",
  "requirejs-text": "2.0.14",
  "requirejs": "2.1.17",
  "bootstrap-dropdown": "*",
  "jquery": "2.1.4",
  "responsejs": "0.9.1"
}

Register and use it as follows:

require.config({
    baseUrl: './',
    paths: {
        knockout: './js/libraries/knockout/dist/knockout',
        text: './js/libraries/requirejs-text/text',
        jquery: './js/libraries/jquery/dist/jquery',
        response: './js/libraries/responsejs/response',
        initComponents: './js/initComponents'
    },
    // Shim configuration for modules that do not expose AMD:
    shim : {
        'response':{
            deps: ['jquery']
        }  
    },
    waitSeconds: 2
});
require(['knockout', 'initComponents', 'response'],
    function (ko, initComponents) {
        var self = this;
        self.weAreSmall = ko.observable();
        Response.create({
            breakpoints: [0, 480, 481]
        });
        Response.action(function() {
             if (Response.band(0, 480)){
                 self.weAreSmall(true);
             } else {
                 self.weAreSmall(false);
             }
        });
        ko.applyBindings(new initComponents());
    }
);
(Note: The above comes from Solid Knockout.)

Take note of "Response.create" and "Response.action" above. You've now set your "weAreSmall" observable, based on the breakpoint that Response.js handles for you.

Now go back to the element in the view where you use your 'logo' CSS class. Use the "ko ifnot" construct (which, yes, looks weird because it looks like a comment, but it's not, that's simply the way you can introduce if clauses via Knockout) into your HTML view:

<!-- ko ifnot: weAreSmall -->
<div>
    <a class="logo" href="http://cocacola.com"></a>
</div>
<!-- /ko -->

You're now using your 'weAreSmall' observable to specify whether the logo is displayed or not. When you look in the NetBeans DOM Browser window, you'll see that there's no div (instead of a hidden logo) when the device size is smaller than 480 px. Compare the screenshot below to the one above, i.e., the logo is not in the DOM anymore, as can be seen in the Brower DOM window in the IDE:

Magically, thanks to Response.js, the logo is swapped back into the DOM when the resolution changes:

The above explanation and all the code comes from around the 20th minute of this recording of a session I did at JavaOne last year with JB Brock. (And we won a Duke's Choice Award for it.) From around the 20th minute, you'll see the above explained excellently by JB, you'll see the Google Maps scenario outlined above, and you'll also see all the code above, all written by JB, again.

Also, note that I have updated Solid Knockout to include the code above, i.e., it now includes Response.js, together with all the sample code above.

In summary, you've now learned how to move from responsive CSS to responsive JavaScript.

Saturday Jun 06, 2015

Knockout.js: Advanced Troubleshooting Techniques

Are you doing anything at all with Knockout.js? If so, sooner or later you'll come across $parent and $root and the other binding context objects. Working with these objects can be quite complex... which is why there are tools to help you specifically with these objects, as demonstrated below in a quick movie:

Friday Jun 05, 2015

HTML5 DataList with Knockout.js

Let's populate an HTML5 DataList with countries via Knockout.js. The result will be as shown below, that is, you will have code completion via your DataList...

...and, when a country is selected, and focus moves out of the DataList (e.g., use the Tab key), its states will be displayed in an unordered list below:

The completed sample code is here:

https://github.com/GeertjanWielenga/Countries

The starting point is to populate an observable array with your countries and states. I found some JavaScript code on-line that did what I needed and you can see that integrated into my sample here:

https://github.com/GeertjanWielenga/Countries/blob/master/public_html/app.js

Now that we have countries and states, let's create a DataList and populate it and, when a country is selected, list its states:

Line 26 above was definitely the trickiest to figure out, where this provided the missing piece of information.

Thursday Jun 04, 2015

HTML5 Fun Pack for NetBeans IDE (Part 1)

What better way to get familiar with the new HTML5 elements and attributes than to have them integrated into the Component Palette in NetBeans IDE?

Below, when you look in the palette on the right side of the screenshot, you see a new HTML5 category, which currently contains four new palette items, for audio, data list (code completion), required (validation), and video: 

When you double-click an item, or drag it into the HTML editor, new elements and attributes related to the palette item are added to the document. Above, you see what happens when "Data List" is clicked, i.e., everything from line 7 to line 15 in the screenshot above is generated from the Data List palette item.

More items are being added to the HTML5 palette (i.e., it is by no means complete, e.g., the new form controls need to be added), so watch this space. Or contribute to the project here:

https://github.com/GeertjanWielenga/HTML5Palette

To see how trivial it is to add new items to the HTML5 palette, click this link to see the "code" (not really code, simply annotations):

https://github.com/GeertjanWielenga/HTML5Palette/blob/master/src/main/java/com/mycompany/html5palette/package-info.java

And to use the new HTML5 palette, install the plugin from here in the Plugin Portal:

http://plugins.netbeans.org/plugin/58560

Note: If you are focused on frontend development, i.e., with PHP and HTML5, make sure you downloaded and installed the "HTML5 & PHP" bundle of NetBeans IDE, which is small and light and comparable to Sublime, (and definitely not the "All" bundle, which is full of things you'll never need):

https://netbeans.org/downloads

Wednesday Jun 03, 2015

Enterprise Web Development with Solid Knockout (Part 2)

Let's now use Solid Knockout to access data from a database:

To get to the above point, I made relatively few changes and, most importantly, I made those changes within the modular framework that Solid Knockout provides. Below, the files in green are new, the files in blue are changed.

To get started, expose data from your database via RESTful Web Services, which is trivial to do in NetBeans IDE. Then use the Knockout Client Generator plugin to generate the skeleton client in your application. You should have the two files shown above in green, i.e., rename them and move them to the places where you see them above.

Now we're going to rewrite those files a bit to make them fit in with the Require.js-based enterprise structure provided by Solid Knockout.

Here's the rewritten "customers.js", which will point to a different RESTful Web Service endpoint for you:

define(['knockout','jquery'], function (ko) {
    function CustomersModel() {
        var self = this;
        self.items = ko.observableArray();
        $.getJSON("http://localhost:8080/mavenproject1/webresources/customers/").
                then(function (customers) {
                    $.each(customers, function () {
                        self.items.push({
                            city: ko.observable(this.city),
                            phone: ko.observable(this.phone),
                            name: ko.observable(this.name),
                            addressline2: ko.observable(this.addressline2),
                            creditLimit: ko.observable(this.creditLimit),
                            addressline1: ko.observable(this.addressline1),
                            state: ko.observable(this.state),
                            fax: ko.observable(this.fax),
                            email: ko.observable(this.email),
                        });
                    });
                });
    }
    return {
        viewModel: CustomersModel,
        template: {
            require: 'text!templates/customers.tmpl.html'
        }
    };
});

And here's the rewritten "customers.tmpl.html":

<div class="container-fluid">
    <table style="margin-top: 1.5cm" border="1">
        <thead>
            <tr>
                <th>Name</th>
                <th>City</th>
                <th>Mail</th>
            </tr>
        </thead>
        <tbody data-bind="foreach: items">
            <tr>
                <td data-bind="text: name"/>
                <td data-bind="text: city"/>
                <td data-bind="text: email"/>
            </tr>
        </tbody>
    </table>
</div>

Finally, in "initComponents.js", add your new component:

ko.components.register("customers", {require: 'js/modules/customers'});

And now, anywhere you want to see your customers, in your HTML view, e.g., in your "index.html", simply use it like this:

<div data-bind="component: {name: 'customers'}"></div>

Tuesday Jun 02, 2015

Enterprise Web Development with Solid Knockout (Part 1)

Solid Knockout is a template that encapsulates best practices for enterprise Knockout.js applications.

Essential to enterprise applications is modularity. Require.js is a popular solution for modularity in JavaScript applications.

Wiring up a Knockout.js application with Require.js is not a trivial task. Rather than figuring out how to include Require.js late in the development cycle, it makes sense to have a modular application from the start. That's the reason for Solid Knockout. It has Require.js included, with CSS classes from Bootstrap for providing a basic header and footer, each of which is a Require.js module, consisting of a JavaScript file and an HTML file.

The screenshot below shows you the structure you get out of the box with Solid Knockout.

When you run the application, you see this, i.e., you see the following header and footer, which you can customize and extend however you like, and then add the domain-specific application content in the main part of the page:


Solid Knockout can be found here:

https://github.com/GeertjanWielenga/SolidKnockout/

Note: Go here to continue to part 2, where you'll learn how to add data via RESTful Web Services to the application.

Monday Jun 01, 2015

Trip Report: NetBeans Day UK

NetBeans Day UK was held on Friday. Attendees ranged from Java teams at financial organizations (e.g., sucdenfinancial.com) to HTML5/JavaScript frontend developers (e.g., farmison.com), to university/college lecturers and students (e.g., from University of Greenwich and University of Kent).


Also read "13 things you missed if you were not at NetBeans Day UK" by Mark Stephens from IDR Solutions, who organized the event, many thanks Mark! (Also go to Twitter and search for #netbeansday to get some short reports on the event.)

It was especially cool to see devs trying out new technologies they learned about on their own codebase, e.g., below you see the Chrome Connector plugin being tried out live during one of the sessions, enabling the Chrome browser and NetBeans IDE to interact with each other for JavaScript/HTML programming:

Next time, the focus will be a lot more on hands on exercises and tutorials, so that attendees can actively participate in the sessions and go home with new code and techniques that will have been taught during the event.

The University of Greenwich was the location, which was a great location, for which we'd really like to thank Gill Windall and others from the university. Other universities participated too, such as the University of Kent, where BlueJ and Greenfoot are developed, and which were demonstrated, as well as a range of other technologies and organizations, such as the very interesting Praxis LIVE and Sharp Statistics. Praxis LIVE is a truly unique application, for doing hypermedia displays, comparable to Quartz Composer and Isadora, except that it is free and open source, created in Java, and full of really awesome features, including integration with TinkerForge.

Steve Millidge from Payara did an excellent all code, (almost) no slide, demo of creating a Java EE application and deploying to Payara, the "baddass fish" of the application servers!



An interesting highlight came from Nick from ionCube who demonstrated switching on and off his office air conditioning from the IDE! Dorine Flies talked about EPIK, while Luke Mayell showed Minecraft running from NetBeans, which was fun (and a great way to introduce programming to kids)! The day was started with a great keynote on the current state of Java, by London JUG leader Ben Evans, as well as a session (by me) about the NetBeans community, roadmap, unique features, and some small NetBeans demos. With the various contacts that have have been established in the UK, we're looking forward to doing more events in the UK, at least one more in England this year, including sessions and courses dealing with Java, JavaScript, Java EE, Cloud, etc.

NetCAT (the NetBeans Community Acceptance Testing program) was well represented by Mark Stephens from England, John McDonnell from Ireland, and Holger Stenger from Germany! During his session, Mark explained in some detail what NetCAT is all about, watch his session here and here on YouTube.

The lunch and coffee breaks were sponsored by Payara, IDR Solutions, EPIK, ionCube, and jClarity. The day ended with a prize draw, where various organizations had contributed prizes, such as books, t-shirts, and licenses. It was the first time that we've had booths at a NetBeans Day. Several of the above ran a booth and had interaction etc with users:


Throughout the day, recordings were done for the next NetBeans Podcast, which should be out sometime in the coming weeks.

It was great for everyone to see the great turn out and the plan is to have the next NetBeans event in the UK toward the end of this year. If you missed this event, no worries, the next one will be announced here and elsewhere, planning will begin once everyone has recovered from the above event!

Thursday May 28, 2015

HTML5: audio, video, 'required', and data list in NetBeans IDE

HTML5 rocks. Take a look at some of the new HTML elements you can work with out of the box.

Each of the screenshots below can be enlarged, so that you can see how NetBeans IDE, with its new support for shadow DOM elements in the upcoming NetBeans IDE 8.1, can help you understand and style these new HTML elements, of which there are several more but these, audio, video, 'required', and data list (i.e., code completion) are especially cool.

Looking forward to exploring more of these and showing how to work with them and style them, e.g., see this.

Also, I'm going to make an HTML5 Palette for NetBeans IDE, which will make it much easier to know which new HTML elements are available, while providing you a GUI for filling in some of the basic values. Code completion and documentation is already integrated, but an HTML5-specific palette would be pretty handy!

Wednesday May 27, 2015

Into the Shadow DOM

Shadow DOM is the subtree of DOM elements that the browser can include into the rendering of a document, without it being rendered into the main document DOM tree.

A complex HTML element, of which several have been introduced in HTML5, such as the HTML5 slider (input type "range"), is constructed via shadow DOM elements. In the HTML elements below, you can see the slider is used, because input type is set to "range", though you do not see the shadow DOM elements that will be used to construct the slider.

Would be handy if you had a tool to inspect the shadow DOM elements within the HTML5 slider and other main DOM elements that have shadow DOM elements. And NetBeans IDE 8.0.2 provides no help, either. Here's how the HTML5 slider above looks in the Browser DOM window of NetBeans IDE 8.0.2:

However, here it is again, in the upcoming NetBeans IDE 8.1, which, as you can see below in the Browser DOM window, includes support for the shadow DOM (click to enlarge the screenshot below to see the full context). Compared to the screenshot above, I can now inspect the shadow DOM by expanding the subnodes of the main input DOM element, while being able to see its shadow DOM elements:

When a shadow DOM element is selected in the Browser DOM window, as shown above, the embedded browser (and the Chrome browser) automatically selects it so that you know where you are and you can quickly find the elements in the browser, even when they are shadow DOM elements.

Moreover, as you can see below, you can select an element within the shadow DOM and then style that specific element in the CSS Styles window:

In the above scenario, I can press the Up arrow key over the height property, which is highlighted above, and then magically I will see the slider in the browser increase in size, because the related style is automatically changed for me, enabling easy and quick tweaking of the style applied to the shadow DOM element.

Further reading and references:

Tuesday May 26, 2015

Knockout.js Community Interview: Ryan Niemeyer

NetBeans IDE, over several releases now, has been building up an awesome set of tools for frontend web development with Knockout.js:

And there's also a handy plugin for generating a Knockout frontend for a Java EE backend:

http://plugins.netbeans.org/plugin/55971/knockout-client-generator

These features include a bunch of different things, such as intellisense and documentation within Knockout's data-bind attribute...

...as well as intellisense for the attributes of Knockout components, as shown here:


So, to explore Knockout more broadly, it's time for the NetBeans community to get to know the Knockout community a bit better! To that end, Ryan Niemeyer, one of the active Knockout community members, has kindly responded to some 'getting to know you' questions I recently sent him.

Hi Ryan, thanks for taking the interview, can you tell us a bit about who you are and what you do?

My name is Ryan Niemeyer and I am a web developer who has been in the software industry for over 16 years. I work for a great company called LeanKit (http://leankit.com). We have an awesome product for visualizing workflows and I have the chance to work with many wonderful and talented folks. I work remotely from the Madison, Wisconsin area and live with my wife and two girls (7 and 4). I have been interested and involved with open source projects as well for the last 5 years, which has been a very enjoyable and valuable experience.

How and when did you get involved with Knockout.js?

I have always been interested in templating and data-binding technologies. I did a lot of XML/XSL work years back and the combining data with a description of how to present it (a template) always made a lot of sense to me. Eventually I started working with jQuery and jQuery templates, which I felt was a quite powerful tool at the time.

Finally, in 2010 when Knockout was first released, it just clicked for me right away. Knockout was able to eliminate so much of the spaghetti code normally required to wire up an application. At the time, I did not have a ton of my own problems to solve with Knockout, so I started getting heavily involved in the Knockout forums and answering questions on StackOverflow. Soon after that, Steve Sanderson, the author of Knockout, asked me to join him on the core team.

You have a very active Knockout.js blog—what are your aims with it and what should one expect to find there?

My blog is at www.knockmeout.net. When I started the blog, there wasn’t a lot of information about Knockout available on-line other than from the official site (http://knockoutjs.com). The blog gives me a chance to share some ideas that I have had for solving problems, introduce plugins that I have written, and provide additional background when there are Knockout releases. My posts have been a bit more infrequent lately, as life is busy at the moment, but I certainly intend on keeping the blog going of the long-term.

What do you consider to be the most awesome features of Knockout.js?

I think that Knockout has a very low barrier to entry. It is easy to learn and stays very focused on data-binding and templating concerns. Knockout definitely provides plenty of extensibility points to allow advanced usage, but you can be productive with it right away.

I believe that another great feature of Knockout is that we have worked hard to maintain backwards compatibility and support browsers all the way back to IE6.

There are many other frameworks in the JavaScript ecosystem, what are the strengths/weaknesses of Knockout.js versus others you may have used, e.g., AngularJS?

Tools like Angular and Ember are definitely focused on providing more of a complete out-of-the-box experience for an entire web application, while Knockout stays focused on just the data-binding and templating pieces.

Some like to build their own stack by combining the most appropriate tools for their situation and Knockout can work well with a variety of other libraries.

What are the tools that you've been using with Knockout.js?

Many people can be pretty productive with Knockout in just about any tool. For most uses, it has a pretty low API surface area. I tend to use WebStorm or Sublime Text 3, but have tried a variety editors.

You've seen a bit of the NetBeans tooling via recent blogs—what do you think of them? 

The tooling around Knockout in NetBeans looks very impressive. Having intellisense and even help information is really useful and powerful.

Anything else you'd like to share with the NetBeans community? 

It is an exciting time for web development, as there are so many tools and solutions that are improving each day. I would encourage everyone to add Knockout.js to their list of solutions to evaluate for their web development projects.

Monday May 25, 2015

New: Maltego Training Video for Absolute Beginners

If you've just downloaded Maltego, which is based on the NetBeans Platform, and you're not sure what to do next, you should watch this new introduction video, released this month:

Sunday May 24, 2015

YouTube: Arquallian and NetBeans IDE

Great new screencast, by Thomas Jost, about using NetBeans with Arquallian:

Also see this excellent article from a while ago on the same topic by NetBeans Dream Team member at Red Hat Markus Eisele:

http://blog.eisele.net/2012/01/arquillian-with-netbeans-glassfish.html

Saturday May 23, 2015

News from the Modular JavaFX Application Framework

The last time I reported on the status of the mFX project was in July last year.

The biggest problem at that time was that the mouse didn't work on the menus. I ran the project again today and I guess my JDK is different (newer) than what I was using at that time because now that problem is fixed, without any changes in my code, i.e., something has been enhanced on the JavaFX level.

Click to enlarge the image below to see a JavaFX application on top of mFX:

The remaining problem is that the window system is still in Swing. If the tabs could somehow be rewritten to JavaFX (and I have tried several things without success) then the entire application would be stylable via CSS.

Aside from that, it's looking pretty good. Above, you see a CSS-styled label that updates itself, via NetBeans Lookup, based on whatever the user has chosen in the selector window in the top right. There's an editor module, a viewer module, and a domain module, in other words, mFX truly enables you to do modular JavaFX development, using all the techniques provided out of the box by the NetBeans Platform, i.e., modularity, loose coupling, and pluggability.

Friday May 22, 2015

javafx.scene.media.MediaPlayer in the NetBeans Platform

Let's integrate javafx.scene.media.MediaPlayer in a NetBeans Platform application so that you can, for example, have an interesting TopComponent like the below.

Steps:

  1. Copy this class into a NetBeans module.

  2. In your TopComponent, which here is named 'NBMediaPlayerTopComponent':
    public NBMediaPlayerTopComponent() {
    
        initComponents();
    
        setName(Bundle.CTL_NBMediaPlayerTopComponent());
        setToolTipText(Bundle.HINT_NBMediaPlayerTopComponent());
    
        setLayout(new BorderLayout());
        JPanel playerpanel = new JPanel();
        final JFXPanel jFXPanel = new JFXPanel();
        playerpanel.add(jFXPanel);
        add(playerpanel, BorderLayout.CENTER);
    
        Platform.setImplicitExit(false);
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                initFxLater(jFXPanel);
            }
        });
    
    }
    
    private static void initFxLater(JFXPanel panel) {
        MediaPlayer mediaPlayer = new MediaPlayer(new Media(MEDIA_URL));
        mediaPlayer.setAutoPlay(true);
        mediaPlayer.setVolume(20.0);
        panel.setScene(new Scene(new MediaControl(mediaPlayer)));
    }
    

References:

http://docs.oracle.com/javafx/2/swing/MediaControl.java.htm

http://stackoverflow.com/questions/22364461/swing-and-javafx

http://stackoverflow.com/questions/15479821/javafx-mediaplayer-volume-trouble-why-the-volume-of-mediaplayer-do-not-chang

https://platform.netbeans.org/tutorials/nbm-javafx.html

Thursday May 21, 2015

Open LaTeX Studio

Open LaTeX Studio is a lightweight LaTeX editor, with LaTeX code syntax highlight, code completion and live preview of the document in edition. It allows generating PDF files from the editor and provides Dropbox support, by allowing to connect the application with the Dropbox account, saving and uploading files to the remote directories and providing version control of the remote files. The application is delivered for the Windows and Linux platforms.

The project is Open source and is developed as a part of the master's thesis of Sebastian Brudziński.

It is built using the NetBeans Platfrorm 8. The code repository is located at:

https://github.com/sebbrudzinski/Open-LaTeX-Studio

and the application website is:

http://sebbrudzinski.github.io/Open-LaTeX-Studio/


Wednesday May 20, 2015

NetBeans Day Twente

Today NetBeans Day was held in Twente, which is an area in the east of the Netherlands, with a high population of grass and farm animals. The turnout was great, exactly as expected, though the narrow focus on MooTools, while relevant for the audience, limited active participation to cows only:

The photo above was taken during the workshop "JavaScript Developers Are Basically Sheep", which had as a subtitle "Weakly Typed Languages Are For The Birds".

Did you miss NetBeans Day Twente? Not to worry, there's NetBeans Day UK coming up end of this month and NetBeans Day Brazil end of the next!

Monday May 18, 2015

Knockout Simplicity for Bootstrap.css (Part 2)

Continuing the theme from the previous blog entry, here's the current state of my 'menubar' component, i.e., this is all I need to put into an HTML file...

...to get this:

The above is a Bootstrap.css menubar, created from the Knockout component shown above.

The HTML below is the template that styles the menubar, notice that there's JavaScript logic, thanks to Knockout, within the template:

Finally, here's the business logic that connects the template to the component, which receives its parameters from the component:


Sunday May 17, 2015

Knockout Simplicity for Bootstrap.css (Part 1)

Imagine you need to create a menubar for your website:

If you had a choice, which of the two below would you choose as the way to express your menubar?

In both cases, you start by declaring Bootstrap.css:

<link href="css/bootstrap.css" rel="stylesheet" type="text/css"/>

However, which of the two would you prefer to use, after you have added the stylesheet reference above?

Option 1:

Option 2:


Of course, it's up to you and I won't judge you either way. However, to me, option 2 is much simpler and more expressive. Plus, I can use it in any website where I need a menubar, i.e., it's a simple lightweight generic tag in my HTML ready to be used anytime I need a menubar. It also means I don't need to type all that error-prone HTML code and it is also a lot more readable, as well. It looks a bit like JSON, while option 1 is very heavily loaded with angle brackets and other superfluous noise.

Option 2 is a Knockout component.

It is created like this, in my 'appViewModel.js' file:

ko.components.register("menubar", {require: 'components/menubar/menuBar'});

The above points to a JavaScript file named 'menuBar.js', which has this content:

define([], function () {
    function MenuBarModel(params) {
        self.menus = [];
        for (var key in params) {
            if (key.substring(0, 3)==('tab')) {
                self.menus.push(params[key]);
            }
        }
    }
    return {
        viewModel: MenuBarModel,
        template: {
            require: 'text!components/menubar/menuBar-template.html'
        }
    };
});

Above you see the 'template' binding points to an HTML file, which has this content:

<div class="navbar">
    <div class="navbar-inner">
        <ul class="nav" data-bind="foreach: menus">
            <li data-bind="css:  { active: $data.substring(0,1) == '*' }">
                <a data-bind="attr: { href: $data.substring($data.indexOf('/')+1) }">
                    <span data-bind="text: $data.substring(1,$data.indexOf('/'))"/>
                </a>
            </li>
        </ul>
    </div>
</div>

And now you can make the menubar a lot fancier: http://www.w3schools.com/bootstrap/bootstrap_case_navigation.asp

By means of the above, we have a simple syntax to define (1) the active menu, (2) the name of the menu, and (3) the URL that is returned when the menu is clicked. The Knockout 'menubar' component figures all these things out under the hood so that the user of the menubar doesn't have to think about it themselves. They simply specify the values that should be passed into the component and the component parses the value and figures out what to do with it.

The above provides a simple and comprehensive architecture for component-based development with JavaScript.

Saturday May 16, 2015

Porting Knockout Components to DukeScript

With Knockout, you can extend the DOM by means of widgets, also known as 'components', such as the "user" component that you see below, which has the parameters "firstName" and "lastName":

As discussed yesterday and the day before in this blog, a component is created in JavaScript, like this:

ko.components.register('user', {
    viewModel: function (params) {
        this.firstName = ko.observable(params.firstName);
        this.lastName = ko.observable(params.lastName);
        this.fullName = ko.pureComputed(function () {
            return this.firstName() + " " + this.lastName();
        }, this);
    },
    template:
        'First Name: <input data-bind="textInput: firstName"/>\
        <br/>\
        Last Name: <input data-bind="textInput: lastName"/>\
        <h2 data-bind="text: fullName"></h2>'
});

As you can see here, by means of 'ko.components.register', you're able to register a new component, which is named 'user' here, consisting of a viewmodel and a template.

Now let's imagine we're using DukeScript, i.e., the WORA framework for Java programmers. Imagine you have several Knockout components like the above, how would you integrate them into your DukeScript application?

One of the Maven projects provided by the DukeScript Maven archetype has "JavaScript Libraries" in its name:

Notice that in the above there's a JavaScript file named 'userEntryComponent.js'. The content of that file is the 'user' component described in code at the start of this blog entry. Also notice that there is a Java source file in the above screenshot, named 'UserEntryWidget.java', which has this content:

package org.demo.ko4j.DemoKO4J.js;

import net.java.html.js.JavaScriptBody;
import net.java.html.js.JavaScriptResource;

@JavaScriptResource(value = "userEntryComponent.js")
public final class UserEntryWidget {

    private UserEntryWidget() {
    }

    @JavaScriptBody(args = {}, body = "")
    public static native void registerComponent();

}

Notice that there is a reference to the JavaScript file, as well as a static method named 'registerComponent'.

OK, congratulations, you have ported your Knockout component to DukeScript, which consists of (1) copying the JavaScript file into the correct place in the DukeScript application structure and (2) registering it via the @JavaScriptResource annotation shown above.

The final step is to use the component. In the 'Main.java' class, i.e., in the Maven project where the client code is defined, you need the following:

public static void onPageLoad() throws Exception {
    Data d = new Data();
    Models.toRaw(d); // this line is required to initialize knockout
    UserEntryWidget.registerComponent();
    d.applyBindings();
}

Notice the two lines in bold above. Notice that we're calling the static method in the UserEntryWidget class above. Also notice that we do not initialize the Data class above, i.e., we do not need to use 'setFirstName' and 'setLastName' on the Data class, because the initialization is done when you make use of the 'user' component, as you can see in the first screenshot above.

That's all you need to do to include a Knockout component in a DukeScript application.

About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« July 2015
SunMonTueWedThuFriSat
   
4
7
11
12
20
30
31
 
       
Today