terça-feira, 24 de junho de 2014

Another World Cup App... Using JavaFX, FXML, Javascript, CSS

The World Cup Brazil is happening! It's exciting to see people from all over the world visiting my country! Today I decided to create another World Cup App, this time I'll use JavaFX, but I won't write any Java code.
It's a simple app to visualize all the world cup matches and click on a game for details about it. I spent less than 3 hours working on the core of the application and a few more hours working on the details.

Getting the resources to create the App

By resources I meant images and to do this I downloaded all the flags images from Fifa site. It was a small and easy scrapping. Notice that all images are in under the following URL: http://img.fifa.com/images/flags/4/{CODE}.png. To download all flags I used the following Python Script:

import urllib2
codes = open('countries_codes.txt', 'r')
for line in codes:
        code = line.replace('\n', '').lower() + '.png'
        img_url = 'http://img.fifa.com/images/flags/4/' + code
        print img_url
        req = urllib2.Request(img_url)
        response = urllib2.urlopen(req)
        img = response.read()
        f = open(code, 'w')
        f.write(img)

I also used to following image as a inspiration to our app layout:



The app view

The view was entirely created on Scene Builder and it was given a styles and IDs to the view components, so from Java we could highlight some parts according to the world cup information.



We have all games displayed on the app and when the user clicks on a game, the game details are showed in a central pane:



The app style

TO change the application to have Brazil colors, we used a very simple CSS file which also changes the appearance of a match when the mouse is on it, see:

.root{
        -fx-base: CornflowerBlue;
        -fx-background: rgb(227,231,239);
}
.TitledPane{
        -fx-text-fill: FIREBRICK;
}
#match_details{
        -fx-background-color: rgb(177,174,218);
}
.match:hover{
        -fx-font: bold 12pt "Calibri";
        -fx-effect: dropshadow(three-pass-box , blue, 20, 0.4 , 0 , 0 );
        -fx-cursor: hand;
}

The app logic

As this is a temporal application, we won't need to create model classes to represent the data, it was used only Javascript to write the application logic!
The logic is simple: we will the app information from a JSON served using HTTP. A good soul scrapped FIFA site to make the results available in JSON. We request this JSON and basically fill our application elements with the JSON. Notice I give an id to every match (that was tedious!) and from the json I fill the data, see:

var matches = downloadMatchesInfo()
...
function downloadMatchesInfo(){
        print("Trying to download the matches information.........")
        var out, scanner
        try{
                var urlStream = new java.net.URL(MATCHES_DATA_URL).openStream()
                scanner = new java.util.Scanner(urlStream, "UTF-8")
                // TODO: save the latest downloaded JSON
        }catch(e){
                print("Couldn't download the updated information, using a cached one.....")
                scanner = new java.util.Scanner(new java.io.File(CACHED_DATA_URL), "UTF-8")
    
        }    
        scanner.useDelimiter("\\A")
        out = scanner.next();
        scanner.close();
        return eval(out);
}


Using eval transform our String into a Javascript object! So I can access the JSON data directly, see how the matches are filled:

function fillMatch(match){
        var viewMatch = $STAGE.scene.lookup("#match_" + match.match_number)
        if(viewMatch && match.home_team.country){
                viewMatch.children[0].image = getImg(match.away_team.code)
                viewMatch.children[1].text = match.status == "future"? "_": match.home_team.goals;
                viewMatch.children[3].text = match.status == "future"? "_": match.away_team.goals;
                viewMatch.children[4].image = getImg(match.home_team.code)
        }
        viewMatch.onMouseClicked = function(e){
                fillMatchDetails(match)
        }
}

function getImg(code){
        var imgUrl = code?"./images/teams/" + code.toLowerCase() + ".png":"./images/no_team.png"
        if(!imgCache[imgUrl])
                imgCache[imgUrl] = new javafx.scene.image.Image(new java.io.FileInputStream(imgUrl))
        return imgCache[imgUrl]

}


See in the code above how easy is to use Javascript structures in a code that deal with Java libraries(particularly see our images cache named imgCache). Notice that when the user clicks on a match, we register a listener to show the match details on the central pane:

function fillMatchDetails(match){
        var s = $STAGE.scene;
        detailsTransition.playFromStart()
        var notPlayedScore = match.status == "completed"?"0":"_"
        s.lookup("#match_home_team").image = getImg(match.home_team.code)
        s.lookup("#match_away_team").image = getImg(match.away_team.code)
        s.lookup("#match_home_score").text = match.home_team.goals?match.home_team.goals:notPlayedScore
        s.lookup("#match_away_score").text = match.away_team.goals?match.away_team.goals:notPlayedScore
        s.lookup("#match_status").text = "Match " + match.status
        s.lookup("#match_time").text =  match.datetime.substring(0, 16)
        s.lookup("#match_location").text =  match.location
}


Instead injecting elements on a controller, I decided to get it by id using the Scene lookup method.

Running the application

The applications isn't compiled, it's interpreted! To run it, you just need to have Java 8 on you path to use the jjs utility. As the code is on github, you can clone it and run:

$ git clone https://github.com/jesuino/another-world-cup-app.git
$ cd another-world-cup-app
$ jjs -fx app.js

You can also set JAVA_HOME on run.sh and make it an executable to run it:

$ chmod +x run.sh
$ ./run.sh

If you are on windows, my girlfriend, Luana, tested it on this "operating system" and she just had to create a run.bat file on the application root directory with the following content:

"C:\Program Files\Java\jre8\bin\jjs" -fx app.js

Notice you might have to change it according to your Java 8 installation.

Conclusion


As you know, it's really easy to create
JavaFX apps and we don't even need to write Java code. We used Javascript to read the resulting JSON and interact with the view. which showed to be a great approach since we didn't have to use any third part library to deal with the JSON.
I could also teach my girlfriend how to run and change the app using Scene Builder and appearance and she is not a Java programmer and she actually changed the style of the application by modifying the CSS!

Here's the final application:





Nenhum comentário:

Postar um comentário

Postar um comentário