<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mikael Lassa on Medium]]></title>
        <description><![CDATA[Stories by Mikael Lassa on Medium]]></description>
        <link>https://medium.com/@mikael.lassa?source=rss-666710bff6dc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*B-G5w6L77nb9bk9FZ8rL_g.jpeg</url>
            <title>Stories by Mikael Lassa on Medium</title>
            <link>https://medium.com/@mikael.lassa?source=rss-666710bff6dc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:33:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mikael.lassa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Validating Identification Numbers: a Java Implementation of the Luhn Algorithm]]></title>
            <link>https://medium.com/@mikael.lassa/validating-identification-numbers-a-java-implementation-of-the-luhn-algorithm-220cacfc9a4b?source=rss-666710bff6dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/220cacfc9a4b</guid>
            <category><![CDATA[luhn-algorithm]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mikael Lassa]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 07:39:08 GMT</pubDate>
            <atom:updated>2023-04-22T07:39:08.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NXhQwaR6FWn-HwLu" /><figcaption>Photo by <a href="https://unsplash.com/@alpridephoto?utm_source=medium&amp;utm_medium=referral">Андрей Сизов</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The Luhn Algorithm, also known as Mod 10 Algorithm, is a widely used formula to check the integrity of several types of identification strings, most notably credit card numbers, though it is also used to verify ID numbers in certain countries, IMEI identificators, and bank routing numbers.</p><p>It is a relatively simple checksum formula developed in the 1960s and still widely used today, as it retains its straightforward use case of validating credit card (and other) numbers against typing errors in an easy and quick manner. The algorithm is in the public domain.</p><h4>The computation</h4><p>An example of this string validation algorithm follows these steps (assuming the string includes the last digit, or check digit):</p><ul><li>Starting from the right of the numeric string, each second digit is multiplied by 2.</li><li>If the result of the multiplication is a two-digit number, the two digits are summed up to each other to obtain a single-digit number.</li><li>All the digits in the resulting string, including the unchanged ones, are summed up together.</li><li>The resulting number is divided by 10: if the division has no remainder, the credit card/ID number is valid.</li></ul><p>This is why the Luhn algorithm is also called “Mod 10 Algorithm”: the integrity of the string relies on the whether the result divided by 10 has any remainder. This process can also be used to calculate the check digit, i.e. the digit that is added to the end of the string to validate it.</p><p>The following example shows the validation of the number 451922. Each second digit is multiplied by 2, and the remaining ones are multiplied by 1, i.e. they remain unchanged. The resulting numbers are all summed up together.</p><pre>Digits       4 | 5 | 1 | 9 | 2 | 2 | <br>Multiplier   2 | 1 | 2 | 1 | 2 | 1 |<br><br>=            8 | 5 | 2 | 9 | 4 | 2 |<br><br>(8 + 5 + 2 + 9 + 4 + 2 ) = 30<br><br>30 % 10 = 0</pre><p>The final sum in this case is 30, which is divisible by 10 without any remainder. This means that code 451922 successfully passes the Luhn algorithm validation.</p><h4>A Java implementation</h4><p>Let’s now implement this in code. The following snippet is one example of how this validation algorithm can be implemented in a Java method:</p><pre>   public static boolean validateNumber(String number){<br>        /*<br>        Validation of user input: blank spaces are removed from the<br>        numeric string. Also, the code ensures that the input is numeric<br>         */<br>        number = number.replaceAll(&quot; &quot;, &quot;&quot;);<br><br>        try{<br>            Long.parseLong(number);<br>        } catch (NumberFormatException e){<br>            System.out.println(&quot;Invalid input&quot;);<br>            return false;<br>        }<br><br>        int sum = 0;<br>        boolean alternateDigit = false;<br><br>        /*<br>        Starting from the right of the string, the code loops through each<br>        digit and multiplies every second digit by 2.<br>         */<br><br>        for(int i = number.length()-1; i &gt;= 0; i--){<br>            int digit = Integer.parseInt(number.substring(i, i+1));<br>            if(alternateDigit){<br>                digit *= 2;<br>                if(digit &gt; 9){<br>                    digit = 1 + (digit % 10);<br>                }<br>            }<br>            sum += digit;<br>            alternateDigit = !alternateDigit;<br>        }<br><br>        return (sum % 10 == 0);<br>    }</pre><p>The method first performs some data validation: it removes all white spaces that are often added to make credit card numbers more readable. It also ensures that the string is only made up of digits, with no extra characters, and handles any resulting NumberFormatException accordingly.</p><p>Then, the code loops through each digit, starting from the right, to implement the steps described in the section above. Each second digit is multiplied by 2, and in cases where this results in a number higher than 9, the two digits are summed up together to compute a one-digit number.</p><p>At each loop iteration, the resulting number is summed up to the sum variable, which is used to keep track of the overall sum. After the loop completes, the method returns true if sum is divisible by 10.</p><p>The complete code can be found on <a href="https://github.com/m-lassa/LuhnValidator">Github</a>.</p><h4>Limitations</h4><p>The primary use case of the Luhn algorithm is to quickly and efficiently identify errors in numeric strings that might indicate a mistyped or otherwise invalid number. It is therefore a good quick formula to ensure that, for example, there are no typing errors or misplaced digits in a credit card number.</p><p>However, the algorithm is not meant as an assurance against fraud or misconduct. It only provides a basic validation of the numeric string and is unable to verify the authenticity of a credit card or identification number. This means that it cannot detect, for example, if a number has been generated for the purpose of circumventing the algorithm by matching its check sum calculation.</p><p>Also, it cannot provide more advanced validation such as checking if the credit card number is associated with a valid bank account. Additional validation checks and security measures should be applied to ensure the integrity and accuracy of any identification code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=220cacfc9a4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Excel Metadata and Security Handling with Java]]></title>
            <link>https://medium.com/@mikael.lassa/simplifying-excel-metadata-and-security-handling-with-java-6daad2cb6798?source=rss-666710bff6dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6daad2cb6798</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[apache-poi]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javafx]]></category>
            <dc:creator><![CDATA[Mikael Lassa]]></dc:creator>
            <pubDate>Sun, 12 Feb 2023 13:25:30 GMT</pubDate>
            <atom:updated>2023-02-12T13:25:30.384Z</atom:updated>
            <content:encoded><![CDATA[<p>Working with Excel spreadsheets at advanced levels might bring about a need for analysing and manipulating metadata or adjacent features, such as security. Java and specific libraries like Apache POI make it easier and faster to extract this information, which can be particularly useful for auditing and tracking purposes, and to modify or operate on it.</p><p>In this post, I’ll provide examples of how Java can be used to simplify and streamline Excel metadata and security manipulation, and how this can be brought together in a simple UI desktop application. The post and the code snippets reference an application I built for this purpose: you can consult the <a href="https://github.com/m-lassa/JavaExcelHandler">full code on Github</a>. Any feedback, bug reports, or contributions to the code are always welcome.</p><p>The following sections provide an overview of the application, and then delve into the backup functionality, the metadata viewer, and the worksheet protection handling code, as well as into how to harmonise these operations within a UI application.</p><h4>Excel Handler Application Overview</h4><p>The Java application used for the examples in this post features a User Interface built with <strong>JavaFX</strong>. The architecture of the project follows the <strong>Model-View-Controller</strong> pattern:</p><ul><li>The Data Model contains the classes that operate on Excel files directly.</li><li>The View is composed of a main window, the appearance of which is defined in a .fxml file.</li><li>The Controller handles user interactions with UI elements, and calls methods from the Data Model classes as appropriate.</li></ul><p>The application makes use of several classes from the java.io (Input/Output) package, which are needed to work with files and data input/output streams. Moreover, some of the classes in the Data Model rely on <strong>Apache POI </strong>5.2.3 libraries. Apache POI is a very useful tool as it allows to create, modify, and extract data from Excel files with ease.</p><h4>The Basics: Backing up Files</h4><p>While the operations described in this article do not handle data in the underlying files directly, it is always good practice to make a back up of the file, just in case. This is done in the application’s Data Model by a class named FileBackupHandler, which contains a method to create a copy of the file, and another one to verify the validity of the given file path.</p><p>The backupFile method makes a backup copy of a specified file. The purpose of this method is to ensure that the original file is not overwritten or lost in case something goes wrong during the modification process. This method takes the original file path as an argument and creates a new file with a different name in the same directory, but with the “_backup” string appended to it to distinguish it from the original. This way, if something goes wrong during the modification process, the original file can be restored from the backup.</p><pre>public static boolean backupFile(String filePath) {<br>        if(!isValidFilePath(filePath)) {<br>            System.out.println(&quot;Please input a correct file path.&quot;);<br>            return false;<br>        } else {<br>            try {<br>                // Get the file name and directory of the original file<br>                File originalFile = new File(filePath);<br>                String fileName = originalFile.getName();<br>                String fileDirectory = originalFile.getParent();<br><br>                // Create the backup file name by adding &quot;_backup&quot; to it<br>                int extensionIndex = fileName.lastIndexOf(&quot;.&quot;);<br>                String backupFileName = fileName.substring(0, extensionIndex) + &quot;_backup&quot; + fileName.substring(extensionIndex);<br>                String backupFilePath = fileDirectory + File.separator + backupFileName;<br>                // Copy the original file to a backup file<br>                Files.copy(Paths.get(filePath), Paths.get(backupFilePath), StandardCopyOption.REPLACE_EXISTING);<br>                return true;<br>            }  catch (IOException e){<br>                e.printStackTrace();<br>                return false;<br>            }<br>        }<br>    }</pre><h4>Extracting Metadata</h4><p>The extraction of metadata is handled by the MetaDataHandler class. It contains the displayProperties method, which creates an instance of the Apache POI XSSFWorkbook class, and calls the appropriate methods to extract the properties of the Excel file. The result of each call is appended to a StringBuilder instance which is then converted to a string and returned as the output. The Controller then uses the content of the string to populate a new UI window that displays the metadata to the user.</p><p>For instance, the following example shows how to retrieve author information from a workbook — a comparable syntax can be followed for most other available properties:</p><pre>XSSFWorkbook workbook = new XSSFWorkbook(inputStream);<br><br>author = workbook.getProperties().getCoreProperties().getCreator();</pre><h4>Handling Worksheet Protection</h4><p>When working with Excel, it is important to understand its different layers of security. In order to properly secure an Excel file, you should encrypt its contents, i.e. set the password at the file level. This will allow read and write access to the whole file only to users who know the password.</p><p>The commonly used worksheet or workbook-level protection, on the other hand, is not intended as a security feature, as it is simply a way to restrict write access, but still allow read access even without the password. If you forget this worksheet-level password, or find yourself in a situation where, for example, the only person who known the password has left the company, you might know that there are a couple of ways around this, without having to deal with the hashing algorithm. One common way to solve this is to make a .zip file from the Excel file, find the .xml files within the .zip folders, and remove the protection string. This, however, carries the risk of making unwanted modifications to the .xml files, which might compromise the integrity of the spreadsheet and its data.</p><p>The following Java method is a simpler way of carrying out this operation almost instantly. In this example, it is implemented as part of the ExcelPasswordRemover class in the Data Model. The code loops through the sheets in the Excel file (represented by a XSSFWorkbook instance) and passes a null value to to the protectSheet method for each sheet. By doing so, the existing password value is overwritten by null, and is therefore effectively removed. A similar line of code does the same at the workbook level. Obviously, you should only perform this kind of operations where you have the authorisation to do so. And as mentioned above, this only works for sheet or workbook protection, and will not work if the file itself is encrypted, which is the correct way of protecting an Excel file from unwanted access. With a similar syntax as the one displayed in the following example, one can manipulate worksheet protection simply by passing the wanted value as a parameter to the protectSheet method.</p><pre>public static boolean removeExcelPassword(String filePath)<br>            throws IOException {<br><br>        if(!isValidFilePath(filePath)) {<br>            System.out.println(&quot;Please input a correct file path.&quot;);<br>            return false;<br>        }<br>        FileInputStream inputStream = new FileInputStream(new File(filePath));<br>        String extension = filePath.substring(filePath.lastIndexOf(&quot;.&quot;)+1);<br>        if(extension.equalsIgnoreCase(&quot;xlsx&quot;) || extension.equalsIgnoreCase(&quot;xls&quot;)){<br>            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);<br>            // Remove password protection from all sheets in the workbook<br>            int numberOfSheets = workbook.getNumberOfSheets();<br>            if (numberOfSheets &gt; 0) {<br>                for (int i = 0; i &lt; numberOfSheets; i++) {<br>                    if(workbook.getSheetAt(i).getProtect()) {<br>                        workbook.getSheetAt(i).protectSheet(null);<br>                    }<br>                }<br>                // Remove password protection from the workbook<br>                workbook.setWorkbookPassword(null, HashAlgorithm.sha512);<br><br>                // Save the workbook to the same file path<br>                FileOutputStream outputStream = new FileOutputStream(filePath);<br>                workbook.write(outputStream);<br>                outputStream.close();<br>                workbook.close();<br>                return true;<br>            }<br>        } else return false;<br>        return false;<br>    }</pre><h4>Bringing it All Together: the Role of the Controller</h4><p>The Controller class in a JavaFX program acts as the mediator between the user interface (the view) and the underlying data (the model). The role of the Controller is to handle user actions, such as button clicks, and coordinate the appropriate operations in the model.</p><p>In this case, the user interface contains buttons to perform the actions described in the sections above. When a button is clicked in the user interface, the event is detected by the Controller and triggers a call to the relevant method in the model. The methods in the Controller additionally display alerts to the user to communicate either the successful completion of the operation, or that the action could not be completed due to errors.</p><p>The reason for choosing this design pattern for this application is that, by separating the logic of the program into the Data Model and the Controller, the application can be more easily maintained and extended. The model classes can be tested and modified independently, and the user interface can be updated without affecting the underlying functionality. This modular design thus makes it easier to build complex programs and improve reliability, maintainability, and scalability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iv8T2rIGOCvyNZ25" /><figcaption>Photo by <a href="https://unsplash.com/it/@orbtalmedia?utm_source=medium&amp;utm_medium=referral">orbtal media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6daad2cb6798" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Java Data Output Streams: a guide to the writeInt method]]></title>
            <link>https://medium.com/@mikael.lassa/mastering-java-data-output-streams-a-guide-to-the-writeint-method-b1165bdd847b?source=rss-666710bff6dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1165bdd847b</guid>
            <category><![CDATA[input-output]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mikael Lassa]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 19:57:09 GMT</pubDate>
            <atom:updated>2023-01-25T19:57:09.933Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I’m going to dive deep into how specific Java IO (Input/Output) classes handle the writing of primitive data onto files. This will be illustrated in particular by the writeInt() method implementation, found in classes such as DataOutputStream and RandomAccessFile. The writeInt() method of the DataOutputStream class is called to output an int value to the underlying output stream. It takes a single argument, which is the int value to be written to the stream, and writes each of its four bytes.</p><p>In this example, the writeInt() method is used to write the int value 123 to the file &quot;test.txt&quot;:</p><pre>DataOutputStream out = new DataOutputStream(new FileOutputStream(&quot;test.txt&quot;));<br>out.writeInt(123);<br>out.close();</pre><p>But how does this actually work? When looking at how the writeInt() method is defined in the DataOutputStream class, we are faced with this code (note that it might change based on your JDK version or libraries that you are using, but the overall concept remains the same):</p><pre>public final void writeInt(int v) throws IOException {<br>        writeBuffer[0] = (byte)(v &gt;&gt;&gt; 24);<br>        writeBuffer[1] = (byte)(v &gt;&gt;&gt; 16);<br>        writeBuffer[2] = (byte)(v &gt;&gt;&gt;  8);<br>        writeBuffer[3] = (byte)(v &gt;&gt;&gt;  0);<br>        out.write(writeBuffer, 0, 4);<br>        incCount(4);<br>    }</pre><h4>The Unsigned Right Shift Operator</h4><p>The method takes an int as a parameter but it ends up writing its value as an array of bytes (writeBuffer[]) to the underlying file. This code uses the bitwise unsigned right shift operator &gt;&gt;&gt; to shift the bits of the int value v to the right by 24, 16, 8, and 0 places, respectively.</p><p>There’s a bit to uncover here, but it’s much easier once we take it one step at a time. I’ll use an example to simplify the explanation of how this actually works.</p><p>First of all, remember that the size of an integer in Java is 4 bytes. A byte is made up of 8 bits, so an integer is 32 bits in size. Let’s take the random integer 738 917 736 to illustrate this. The binary representation of 738 917 736 is the following sequence of 32 bits:</p><pre>00101100 00001010 11111101 01101000</pre><p>What the writeInt() method does, essentially, is to break up the integer into four separate bytes (sequences of 8 bits). This is what the four lines with the &gt;&gt;&gt; operator do: they isolate each byte of the integer and add them to the array, to then write each byte separately to the output stream.</p><p>The &gt;&gt;&gt; operator shifts the bits to the right by the specified number of places, replacing the bits to the left with 0s. Let’s take the first line:</p><pre>writeBuffer[0] = (byte)(v &gt;&gt;&gt; 24);</pre><p>The whole 32-bit binary number is shifted 24 positions to the right, so the the resulting sequence is what follows:</p><pre>00000000 00000000 00000000 <strong>00101100</strong></pre><p>This is stored as the first element of the array. Note that the first byte has now shifted to the end of the sequence.</p><p>Then a very similar thing is done by shifting the original binary sequence 16 bits to the right, thus resulting in:</p><pre>00000000 00000000 00101100 <strong>00001010</strong></pre><p>Now the second byte from the original sequence takes up the last byte position. Then we shift the original sequence 8 bits to the right:</p><pre>00000000 00101100 00001010 <strong>11111101</strong></pre><p>And eventually, we shift 0 bits to the right, i.e. we use the same sequence we had at the beginning:</p><pre>00101100 00001010 11111101 <strong>01101000</strong></pre><p>The elements in the array are then passed to the write method. It is important to understand that the write method writes one byte at the time, and specifically the eight lowest order bits of the argument, i.e. the last eight bits.</p><pre>00000000 00000000 00000000 <strong>00101100</strong><br>00000000 00000000 00101100 <strong>00001010</strong><br>00000000 00101100 00001010 <strong>11111101</strong><br>00101100 00001010 11111101 <strong>01101000</strong></pre><p>When you take the last byte (or 8 bits) from each of the four sequences above, you get the original 32-bit sequence representing the original full integer value, now written down to the output stream. This is how an integer is broken down and passed to the write() method.</p><h4>The 0xFF Operation</h4><p>You might also find this alternative version of the writeInt()method:</p><pre>public final void writeInt(int v) throws IOException {<br>        write((v &gt;&gt;&gt; 24) &amp; 0xFF);<br>        write((v &gt;&gt;&gt; 16) &amp; 0xFF);<br>        write((v &gt;&gt;&gt;  8) &amp; 0xFF);<br>        write((v &gt;&gt;&gt;  0) &amp; 0xFF);<br>    }</pre><p>Here the bitwise operator &amp; is used between the result of the unsigned right shift operation and the hexadecimal value 0xFF — this is done to retain the eight lowest order bits. Note that the binary representation of 0xFF is 00000000 00000000 00000000 11111111. When two binary numbers are compared with the &amp;operator, each bit is compared with the bit in the corresponding position in the other number — the possible results of comparing bits are: 1&amp;1 = 1 ; 1&amp;0 = 0 ;0&amp;0 = 0 . The result with the original integer in our example is what follows:</p><pre>00101100 00001010 11111101 01101000<br>&amp;<br>00000000 00000000 00000000 11111111   //0xFF<br>= <br>00000000 00000000 00000000 <strong>01101000</strong></pre><p>This operation is done four times, each time the bits are shifted with the &gt;&gt;&gt;operator, in the way described earlier, to get each of the four bytes that comprise the int. As you see, the use of 0xFF allows to easily retain the last byte of the operation, which is what is written to the output stream by the write() method.</p><p>Knowing how integers are handled in data output streams, one gets a grasp of how numeric values in Java are written to files: for instance, to write a long value, the same steps are taken, but the output is eight bytes instead of four. Working with input/output and understanding the way Java handles this might not always be straightforward, but having an understanding of some of the finer details of data reading and writing can be a useful skill in several domains and go a long way in complementing Java skills.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*49EDwKr8KfFJfh5C" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1165bdd847b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting the stage: getting a grasp on User Interface building with JavaFX]]></title>
            <link>https://medium.com/@mikael.lassa/setting-the-stage-getting-a-grasp-on-user-interface-building-with-javafx-54fb11fd397a?source=rss-666710bff6dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/54fb11fd397a</guid>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[javafx-tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javafx]]></category>
            <dc:creator><![CDATA[Mikael Lassa]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 18:55:14 GMT</pubDate>
            <atom:updated>2023-01-15T18:55:14.061Z</atom:updated>
            <content:encoded><![CDATA[<p>While learning and practicing my Java skills, I recently got acquainted with JavaFX, a rather well-known platform for building user interfaces for Java applications. Its popularity is unsurprising: it offers a wide range of tools and features for creating functional user interfaces that work across a range of devices and operating systems.</p><p>In this blog post I’ll go through a few learnings and present my understanding of some of the core concepts of JavaFX which I believe to be useful to anyone approaching this tool. I’ll be referencing code from the first application that I wrote with JavaFX, a desktop App that displays a list of contacts and allows the user to perform a number of operations to edit/customize the list. The full code is available on <a href="https://github.com/m-lassa/ContactApp">GitHub</a>.</p><h4><strong>Model-View-Controller</strong></h4><p>Understanding JavaFX requires a certain degree of understanding of the Model-View-Controller (MVC) software design pattern. In simple terms, the “view” represents the user interface, the “model” represents the underlying data or business logic, and the “controller” acts as a mediator, connecting the view and the model.</p><p>It is this separation of roles that arguably helps keep the code organized and easier to maintain: the user only directly interacts with the View, and the underlying data (the Model) can only be reached and manipulated by the user through the operations allowed within the confines of the UI. The Controller has the key functionality of handling events and input, and acting as the connection between the other two parts of the application.</p><h4>FXML</h4><p>A common way of building user interfaces in JavaFX is to write FXML, which is a markup language used specifically for defining user interface elements, directly based on XML. There are tools designed at aiding the construction of UIs, such as SceneBuilder, but I would generally advise to learn to write FXML manually first before using such tools, as this knowledge will be invaluable when the need to debug UI issues arises.</p><p>The example below is an extract from the main.fxml code of the Contact List application to illustrate the FXML syntax. The whole code is wrapped within an element called BorderPane, a UI style that divides the window into top, left, right, bottom and center sections. The top section in the extract below contains the Menu Bar, which in turn contains a number of Menu Items. For each of these, the text attribute defines the text displayed on the item on screen, while the onAction attribute includes the name of a method that regulates the behavior of the item once the user interacts with it. The actual method is defined in the Controller code, and annotated with the FMXL annotation to indicate the link to the FXML file.</p><pre>&lt;top&gt;<br>        &lt;MenuBar BorderPane.alignment=&quot;CENTER&quot;&gt;<br>            &lt;menus&gt;<br>                &lt;Menu mnemonicParsing=&quot;false&quot; text=&quot;File&quot;&gt;<br>                    &lt;items&gt;<br>                        &lt;MenuItem mnemonicParsing=&quot;false&quot; onAction=&quot;#handleExit&quot; text=&quot;Exit&quot; /&gt;<br>                    &lt;/items&gt;<br>                &lt;/Menu&gt;<br>                &lt;Menu mnemonicParsing=&quot;false&quot; text=&quot;Contacts&quot;&gt;<br>                    &lt;items&gt;<br>                        &lt;MenuItem mnemonicParsing=&quot;false&quot; onAction=&quot;#showContactDialogue&quot; text=&quot;Add&quot; /&gt;<br>                        &lt;SeparatorMenuItem /&gt;<br>                        &lt;MenuItem mnemonicParsing=&quot;false&quot; onAction=&quot;#editSelectedItem&quot; text=&quot;Edit&quot; /&gt;<br>                        &lt;SeparatorMenuItem /&gt;<br>                        &lt;MenuItem mnemonicParsing=&quot;false&quot; onAction=&quot;#deleteSelectedItem&quot; text=&quot;Delete&quot; /&gt;<br>                    &lt;/items&gt;<br>                &lt;/Menu&gt;<br>            &lt;/menus&gt;<br>        &lt;/MenuBar&gt;<br>    &lt;/top&gt;</pre><h4>The Controller</h4><p>The Controller contains the core of the code connecting the View to the Data and the methods handling user input and interaction. The Controller is linked to an FXML file by adding fx:controller=&quot;com.contactapp.Controller&quot; within the code, where the text within double quotes specifies the location of the Controller class. All fields and methods that refer to elements in the related FXML file need to be annotated with the FXML annotation. The name of annotated fields must be the same as the fx:id within the corresponding FXML item.</p><p>This is an example of a TableColumn item in the main.fxml file:</p><pre>&lt;TableColumn fx:id=&quot;firstNameCol&quot; prefWidth=&quot;75.0&quot; text=&quot;First Name&quot; /&gt;</pre><p>The Controller.java file defines a TableColumn field with the same name as the corresponding FXML item; note the FXML annotation before the field declaration:</p><pre>@FXML<br>    private TableColumn&lt;Contact, String&gt; firstNameCol = new TableColumn&lt;Contact, String&gt;(&quot;First Name&quot;);</pre><p>The Controller generally includes the initialize() method, which is called at runtime. In the Contact List application, this method is used to load the list of contacts from the underlying file and populate the view. The contact data is added to a list that is made filterable, and contact names are sorted by last name. This is done using the FilteredList&lt;&gt; and SortedList&lt;&gt; classes.</p><pre>FilteredList&lt;Contact&gt; filteredList = new FilteredList&lt;&gt;(contactData.getContacts(), p -&gt; true);<br><br>SortedList&lt;Contact&gt; sortedList = new SortedList&lt;&gt;(filteredList, new Comparator&lt;Contact&gt;() {<br>            @Override<br>            public int compare(Contact o1, Contact o2) {<br>                return o1.getLastName().compareTo(o2.getLastName());<br>            }<br>        });<br><br>contactTableView.setItems(sortedList);</pre><p>One of the advantages of this approach is to make the list searchable. The search function is implemented by adding a ChoiceBox and a TextField in the FXML code. The ChoiceBox allows the user to select either the first or the last name as a search parameter, and the TextField acts as a search field. The behavior is implemented in the Controller code as follows:</p><pre>searchField.textProperty().addListener((obs, oldValue, newValue) -&gt; {<br>            if(searchChoice.getValue() == &quot;First Name&quot;){<br>                filteredList.setPredicate(p -&gt; p.getFirstName().toLowerCase().contains(newValue.toLowerCase().trim()));<br>            } else if(searchChoice.getValue() == &quot;Last Name&quot;){<br>                filteredList.setPredicate(p -&gt; p.getLastName().toLowerCase().contains(newValue.toLowerCase().trim()));<br>            }<br>        });</pre><p>The Controller code, as stated above, also includes all the methods that run when the user interacts or clicks on specific items of the UI. For example, when the user clicks on the Delete item in the Menu, the deleteSelectedItem() method runs. This method first checks that the user has selected an item from the displayed contact list, and if not, the application displays an alert.</p><pre>@FXML<br>    public void deleteSelectedItem(){<br>        //get selected item<br>        Contact selectedContact = contactTableView.getSelectionModel().getSelectedItem();<br><br>        if (selectedContact == null){<br>            Alert itemSelAlert = new Alert(Alert.AlertType.INFORMATION);<br>            itemSelAlert.setContentText(&quot;No item selected.&quot;);<br>            itemSelAlert.setHeaderText(null);<br>            itemSelAlert.showAndWait();<br>        } else {<br>            Alert alert = deleteItemAlert();<br>            alert.setContentText(&quot;Delete &quot; + selectedContact.getFirstName() + &quot; &quot; + selectedContact.getLastName() + &quot;?&quot;);<br>            Optional&lt;ButtonType&gt; result = alert.showAndWait();<br>            //delete from observable list once OK button is pressed<br>            if (selectedContact != null) {<br>                if (result.isPresent() &amp;&amp; (result.get() == ButtonType.OK)) {<br>                    contactData.deleteContact(selectedContact);<br>                    contactData.saveContacts();<br>                }<br>            }<br>        }<br>    }</pre><h4>The stage and the scene</h4><p>Having an overview of the above, it is useful to have a look at how a JavaFX App is run. The main entry point for a JavaFX application is the JavaFX Application class. It provides a starting point for the application, as well as a container for the main JavaFX stage. The Application class must be extended and its start() method must be overridden to create the initial scene (though this might be taken care of automatically by the IDE). The main method invokes the static launch() method from the Application class: interestingly, the inclusion of the main method and the call to launch() are not necessarily needed in order to run a JavaFX application. When starting the application, JavaFX creates the main thread, builds an instance of the Application class, and runs the start() method.</p><p>The theater metaphors are apparent in this layout. The stage, similar to the main stage in a theatre play, in a JavaFX application is used as a top-level container for all other JavaFX elements. The scene, on the other hand, is like the setting of a play, containing all the visual elements of the performance. It fundamentally represents the content displayed within a single window of the application. The stage can have multiple scenes, but only one is displayed at a time, similar to how a theater can have multiple sets for a play but only one is used in each act.</p><pre>public class Main extends Application {<br>    @Override<br>    public void start(Stage stage) throws IOException {<br>        FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource(&quot;main.fxml&quot;));<br>        Scene scene = new Scene(fxmlLoader.load(), 800, 500);<br>        stage.setTitle(&quot;Contact List&quot;);<br>        stage.setScene(scene);<br>        stage.show();<br>    }<br>}</pre><p>The above are just a few examples of the use of JavaFX to build user interfaces in a desktop application, and how it’s been used in this particular project, hopefully providing an overview of the potential that this platfom has. It is a powerful tool, and with some practice and patience, it allows any Java developer to build beautiful UIs for Java applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54fb11fd397a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>