Pular para o conteúdo principal

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:





Comentários

Postagens mais visitadas deste blog

Simplest JavaFX ComboBox autocomplete

Based on this Brazilian community post , I've created a sample Combobox auto complete. What it basically does is: When user type with the combobox selected, it will work on a temporary string to store the typed text; Each key typed leads to the combobox to be showed and updated If backspace is type, we update the filter Each key typed shows the combo box items, when the combobox is hidden, the filter is cleaned and the tooltip is hidden:   The class code and a sample application is below. I also added the source to my personal github , sent me PR to improve it and there are a lot of things to improve, like space and accents support.

Genetic algorithms with Java

One of the most fascinating topics in computer science world is Artificial Intelligence . A subset of Artificial intelligence are the algorithms that were created inspired in the nature. In this group, we have Genetic Algorithms  (GA). Genetic Algorithms  To find out more about this topic I recommend the following MIT lecture and the Nature of Code book and videos created by Daniel Shiffman. Genetic Algorithms using Java After I remembered the basics about it, I wanted to practice, so I tried my own implementation, but I would have to write a lot of code to do what certainly others already did. So I started looking for Genetic Algorithm libraries and found Jenetics , which is a modern library that uses Java 8 concepts and APIs, and there's also JGAP . I decided to use Jenetics because the User Guide was so clear and it has no other dependency, but Java 8. The only thing I missed for Jenetics are more small examples like the ones I will show i...

Dancing lights with Arduino - The idea

I have been having fun with Arduino these days! In this article I am going to show how did I use an electret mic with Arduino to create a Dancing Lights circuit. Dancing Lights   I used to be an eletronician before starting the IT college. I had my own electronics maintenance office to fix television, radios, etc. In my free time I used to create electronic projects to sell and I made a few "reais" selling a version of Dancing lights, but it was too limited: it simply animated lamps using a relay in the output of a 4017 CMOS IC. The circuit was a decimal counter  controlled by a 555. 4017 decimal counter. Source in the image When I met Arduino a few years ago, I was skeptical because I said: I can do this with IC, why should I use a microcontroller. I thought that Arduino was for kids. But now my pride is gone and I am having a lot of fun with Arduino :-) The implementation of Dancing Lights with Arduino uses an electret mic to capture the sound and light leds...