• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Create a VM ($25 Credit)
  • Buy a Domain
  • 1 Month free Back Blaze Backup
  • Other Deals
    • Domain Email
    • Nixstats Server Monitoring
    • ewww.io Auto WordPress Image Resizing and Acceleration
  • About
  • Links

IoT, Code, Security, Server Stuff etc

Views are my own and not my employer's.

Personal Development Blog...

Coding for fun since 1996, Learn by doing and sharing.

Buy a domain name, then create your own server (get $25 free credit)

View all of my posts.

  • Cloud
    • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
    • How to buy a new domain and SSL cert from NameCheap, a Server from Digital Ocean and configure it.
    • Setting up a Vultr VM and configuring it
    • All Cloud Articles
  • Dev
    • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
    • How to setup pooled MySQL connections in Node JS that don’t disconnect
    • NodeJS code to handle App logins via API (using MySQL connection pools (1000 connections) and query parameters)
    • Infographic: So you have an idea for an app
    • All Development Articles
  • MySQL
    • Using the free Adminer GUI for MySQL on your website
    • All MySQL Articles
  • Perf
    • PHP 7 code to send object oriented sanitised input data via bound parameters to a MYSQL database
    • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
    • Measuring VM performance (CPU, Disk, Latency, Concurrent Users etc) on Ubuntu and comparing Vultr, Digital Ocean and UpCloud – Part 1 of 4
    • Speeding up WordPress with the ewww.io ExactDN CDN and Image Compression Plugin
    • Setting up a website to use Cloudflare on a VM hosted on Vultr and Namecheap
    • All Performance Articles
  • Sec
    • Using the Qualys FreeScan Scanner to test your website for online vulnerabilities
    • Using OWASP ZAP GUI to scan your Applications for security issues
    • Setting up the Debian Kali Linux distro to perform penetration testing of your systems
    • Enabling TLS 1.3 SSL on a NGINX Website (Ubuntu 16.04 server) that is using Cloudflare
    • PHP implementation to check a password exposure level with Troy Hunt’s pwnedpasswords API
    • Setting strong SSL cryptographic protocols and ciphers on Ubuntu and NGINX
    • Securing Google G Suite email by setting up SPF, DKIM and DMARC with Cloudflare
    • All Security Articles
  • Server
    • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
    • All Server Articles
  • Ubuntu
    • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
    • Useful Linux Terminal Commands
    • All Ubuntu Articles
  • VM
    • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
    • All VM Articles
  • WordPress
    • Speeding up WordPress with the ewww.io ExactDN CDN and Image Compression Plugin
    • Installing and managing WordPress with WP-CLI from the command line on Ubuntu
    • How to backup WordPress on a host that has CPanel
    • Moving WordPress to a new self managed server away from CPanel
    • Moving a CPanel domain with email to a self managed VPS and Gmail
    • All WordPress Articles
  • All

java

Useful Java FX Code I use in a project using IntelliJ IDEA and jdk1.8.0_161.jdk

September 15, 2018 by Simon

This is some useful Java FX Code I use in a project using IntelliJ IDEA and jdk1.8.0_161.jdk. I am sharing this code here for the #100DaysOfCode readers and people looking for code answers.

Aside

If you have not read my previous posts I have now moved my blog to the awesome UpCloud host (signup using this link to get $25 free UpCloud VM credit). I compared Digital Ocean, Vultr and UpCloud Disk IO here and UpCloud came out on top by a long way (read the blog post here). Here is my blog post on moving from Vultr to UpCloud.

Buy a domain name here

Domain names for just 88 cents!

As promised, Java code.

Background

I am developing a Java (Windows/Mac/Linux) JavaFX app to assist me (and others) click their way through a Server deployment (domain name purchase, email setup, DNS etc) to the configuration (server host, operating, web server, database etc) to securing (DNSSEC, SPF, DMARC, Firewall etc).

I want to automate much of what I have learned over the last 2 years building apps and services (see all blog DevSecOps posts here: https://fearby.com/all/ ) on a self-managed Linux stack. I love the lower cost, higher security and flexibility of deploying self-managed servers on Linux (I love UpCloud) but not the command line interactions (that’s why I am learning Java, I do not want to develop another web-based GUI as I find them less secure than a good SSH connection). I have been developing on Windows since 1999.

Now show me Jave code.

Save date-time variables in Controller Initialize event to use in Logging

I like to log console events to a filename that is the date-time an app was started.  Add this to “public class Controller implements Initializable”

public Date todaysDateTime = new Date();
DateFormat datetimeFileNameCompatible = new SimpleDateFormat("dd-MMM-yyyy HH-mm-ss.S");
public String strLogFileTimeFilename = "zAPPDISCO - " + datetimeFileNameCompatible.format(todaysDateTime);

Now the log filename can be used below in a log function (DoLog).

Read Ini File

Download http://ini4j.sourceforge.net/ (binary files) and add ini4j-0.5.4.jar to your source folder (or use Maven etc to download the package)

Import the ini4j class to your Controller.

import org.ini4j.Ini;

Sample appname.ini file

# Ini file comment goes here

[config]
forceoffline = false
log = true

[settings]
checkipatstartup = true
checkinternetconnectionatstartup = true

[app]
name=blah blah app name
app_major = 1
appminor = 0
apprevision = 18

[mainwindow]
mainwidth = 1619.0
mainheight = 1119.0
mainleft = 147.0
maintop = 44.0

[settingswindow]
settingswidth = 1286.0
settingsheight = 1010.0
settingsleft = 9.0
settingstop = 153.0

Load an Ini file

objIni = new Ini();
System.out.println("  - Opening app.ini" );
try {
    objIni.load( new FileReader("src/appname/appname.ini"));
    System.out.println("   - Loaded INI (OK)" );

} catch (IOException ex) {
    System.out.println("   - Error Loading appname.ini ( " + ex.toString() + ")");

}

Now we are ready to load values from the loaded Ini file.

Load a Boolean from Ini file

I like to set if an app can talk to the net (by checking an Ini file to see if a user does not want online activity).

private Boolean FORCE_OFFLINE = false;
FORCE_OFFLINE = objIni.get("config","forceoffline",boolean.class);

Load String from an Ini File

System.out.println (" - App Name: " + objIni.get("app","name"));

Global Variables Class

package appname;

public class GlobalVariables {

    public int APP_MAJOR = 0;
    public int APP_MINOR = 0;
    public int APP_REVISION = 18;

    //etc
}

Copy the global variables class in a new controller, add the following code to your new controller’s “public class Controller implements Initializable” function

GlobalVariables global = new GlobalVariables();

Read the constants in the global variable class (copy)

DoLog("Started App Disco (v" + global.APP_MAJOR + "." + global.APP_MINOR  + "." + global.APP_REVISION + ") - https://fearby.com");

Log function that writes to the stdout console and physical log file if desired (set in the ini file)

private void DoLog(String logThis) { 
    // Log to std out
    System.out.println(logThis); 

    // Write to log file
    try{
    	// Declare a new Ini object
        objIni = new Ini();

        System.out.println("  - Opening appname.ini" );
        try {
            objIni.load( new FileReader("src/appname/appname.ini"));
            System.out.println("   - Loaded INI (OK)" );
        } catch (IOException ex) {
        	// Error
            System.out.println("   - Error Reading from appname.ini ( " + ex.toString() + ")");
        }

        // Check the ini file and see if the user wants to out output a log file.
        System.out.println("    - Reading [config] section in Ini file" );

        Boolean DO_LOG;
        DO_LOG = objIni.get("config","log",boolean.class);
        System.out.println("     - DO_LOG = " + DO_LOG.toString() );

        // Does the use want the console to be logged to a date stamped file too?
        if (DO_LOG == true) {
            
            // Append To File
            FileWriter fstream = new FileWriter( strLogFileTimeFilename.toString() + ".log", true);
            BufferedWriter out = new BufferedWriter(fstream);

            // Get Latest Time to prefix to the log entry
            Date todaysDateTimeLog = new Date();
            DateFormat datetimeHumanReadableFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            String strLogFileTimeHuman = datetimeHumanReadableFormat.format(todaysDateTimeLog);

            // Log Desired Line
            String strLogThisTS = strLogFileTimeHuman.toString() + " = " +  logThis;
            out.write(strLogThisTS + "\n");

            //Close the output stream
            out.close();

        } else {
            //System.out.println("      - Skipping logging as set in the ini file.." );
        }


    } catch (Exception e){
    	//Catch exception if any
        // todo: Need to write to System.out.printl to prevent loop
        System.out.println ("Error: " + e.getMessage());  
        
    }
}

Get Contents from URL

private static String getContentsFromURL(String theUrl)
{
    StringBuilder content = new StringBuilder();

    try
    {
        // create a url object
        URL url = new URL(theUrl);

        //todo: Add Newwor check code
        
        URLConnection urlConnection = url.openConnection();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

        String line;

        while ((line = bufferedReader.readLine()) != null)
        {
            content.append(line + "\n");
        }
        bufferedReader.close();
    }
    catch(Exception e) {
        e.printStackTrace();
    }

    return content.toString();
}

Test the internet connection by downloading the contents of a URL

String isup = getContentsFromURL("https://audit.fearby.com/isup/");
System.out.println( "Is UP: " + isup.trim().toUpperCase().toString());

Get the IPV4 address of the calling client

String isup = getContentsFromURL("https://audit.fearby.com/ip/");
System.out.println( "Is UP: " + isup.trim().toUpperCase().toString());

The IP page contains

<?php
echo htmlspecialchars($_SERVER['REMOTE_ADDR'], ENT_QUOTES, 'UTF-8');
?>

SSH to a server and run a command

This is handy for connecting to a server via SSH (and using an SSH passphrase, not a system username password). This is using the Jsch library from http://www.jcraft.com/jsch/

try {
    JSch jsch = new JSch();

    String user = "sshusername";
    DoLog("User: " + user);

    String host = "yourserver.com";
    DoLog("Host: " + host);

    int port = 22;
    DoLog("Port: " + port);

    String privateKey = System.getProperty("user.dir") + "/" +  "yourserver.rsa";
    DoLog("Private Key: " + System.getProperty("user.dir") + "/" +  "yourserver.rsa");

    String sshPassPhrase = "@dd-y0ur-really-str0ng-ssh-pa$word-h3r3";

    DoLog("Adding ssh key passphrase to session");
    jsch.addIdentity(privateKey, sshPassPhrase);
    DoLog("Private Key added to ssh session");

    Session session = jsch.getSession(user, host, port);
    DoLog("Session Created");

    java.util.Properties config = new java.util.Properties();
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no

    DoLog("SSH Config: StrictHostKeyChecking: no");
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);

    DoLog("Connecting");
    session.connect();

    DoLog("Preparing Remote Command");
    String command = "uptime";

    Channel channel = session.openChannel("exec");
    ((ChannelExec)channel).setCommand(command);
    channel.setInputStream(null);
    ((ChannelExec)channel).setErrStream(System.err);

    InputStream input = channel.getInputStream();
    channel.connect();

    try {
        InputStreamReader inputReader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(inputReader);
        String line = null;
        while((line = bufferedReader.readLine()) != null){
            System.out.println(line);
        }
        bufferedReader.close();

        inputReader.close(); }
    catch (IOException ex) {
        ex.printStackTrace();
    }
    channel.disconnect();

    session.disconnect();
    DoLog("SSH session disconnected.....");


} catch (Exception e) {
    System.err.println(e);
}

Output:

16:32:06 up 7 days, 14:59, 1 user, load average: 0.08, 0.02, 0.01

Read more on RSA keys here.

Generate an RSA key here.

Upload a file to a server via SCP over SSH

try {
    JSch jsch = new JSch();

    String user = "sshusername";
    DoLog("User: " + user);

    String host = "yourserver.com";
    DoLog("Host: " + host);

    int port = 22;
    DoLog("Port: " + port);

    String privateKey = System.getProperty("user.dir") + "/" +  "yourserver.rsa";
    DoLog("Private Key: " + System.getProperty("user.dir") + "/" +  "yourserver.rsa");

    String sshPassPhrase = "@dd-y0ur-really-str0ng-ssh-pa$word-h3r3";
    DoLog("Adding ssh key passphrase to session");
    
    jsch.addIdentity(privateKey, sshPassPhrase);
    DoLog("Private Key added to ssh session");

    Session session = jsch.getSession(user, host, port);
    DoLog("Session Created");

    java.util.Properties config = new java.util.Properties();

    //session.setConfig(
    //        "PreferredAuthentications",
    //        "publickey,gssapi-with-mic,keyboard-interactive,password");

    // disabling StrictHostKeyChecking may help to make connection but makes it insecure
    // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no

    DoLog("SSH Config: StrictHostKeyChecking: no");
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);

    DoLog("Connecting");
    session.connect();


    DoLog("Preparing SFTP");
    Channel channel = session.openChannel("sftp");
    channel.setInputStream(System.in);
    channel.setOutputStream(System.out);
    channel.connect();

    ChannelSftp c = (ChannelSftp) channel;
    String fileName = "upload.txt";
    DoLog("Uplaoding file: " + fileName + " to " + "/");
    c.put(fileName, "/");
    c.exit();
    DoLog("Done Uploading File");
    channel.disconnect();



} catch (Exception e) {
    System.err.println(e);
}

On the server:

cat /upload.txt
>Hello World

Encrypt Text (AES/CBC/PKCS5/SHA-256)

public static byte[] encrypt(String strInput, String strPasswordKey) throws Exception {
    System.out.println("\n\nEncrypt()");
    byte[] clean = strInput.getBytes();

    // Generating IV
    int ivSize = 16;

    byte[] iv = new byte[ivSize];
    SecureRandom strRandom = new SecureRandom();
    
    strRandom.nextBytes(iv);
    IvParameterSpec ivParamSpec = new IvParameterSpec(iv);
    
    // Hashing key
    MessageDigest strDigest = MessageDigest.getInstance("SHA-256");
    
    strDigest.update(strPasswordKey.getBytes("UTF-8"));
    byte[] keyBytes = new byte[16];
    
    System.arraycopy(strDigest.digest(), 0, keyBytes, 0, keyBytes.length);
    SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
    
    // Encrypt
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParamSpec);

    byte[] encrypted = cipher.doFinal(clean);
    
    // Combine IV and encrypted part
    byte[] encryptedIVAndText = new byte[ivSize + encrypted.length];

    System.arraycopy(iv, 0, encryptedIVAndText, 0, ivSize);
    
    System.arraycopy(encrypted, 0, encryptedIVAndText, ivSize, encrypted.length);

    String senctext = new String(encrypted, StandardCharsets.UTF_8);

    System.out.println("   encrypted: " + senctext.toString() + ", encryptedIVAndText: " + encryptedIVAndText.toString() + ", size: " + ivSize + ", length: " + encrypted.length);

    return encryptedIVAndText;
}

Decrypt Text (AES/CBC/PKCS5/SHA-256)

public static String decrypt(byte[] encryptedIvTextBytes, String strPasswordKey) throws Exception {
    System.out.println("\n\ndecrypt()");
    int ivSize = 16;
    int keySize = 16;

    // Extract IV
    byte[] iv = new byte[ivSize];
    System.arraycopy(encryptedIvTextBytes, 0, iv, 0, iv.length);
    IvParameterSpec ivParamSpec = new IvParameterSpec(iv);

    // Extract encrypted part
    int encryptedSize = encryptedIvTextBytes.length - ivSize;
    byte[] encryptedBytes = new byte[encryptedSize];
    System.arraycopy(encryptedIvTextBytes, ivSize, encryptedBytes, 0, encryptedSize);

    // Hash key
    byte[] keyBytes = new byte[keySize];
    MessageDigest strDigest = MessageDigest.getInstance("SHA-256");
    strDigest.update(strPasswordKey.getBytes());
    System.arraycopy(strDigest.digest(), 0, keyBytes, 0, keyBytes.length);
    SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

    // Decrypt
    Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParamSpec);
    byte[] decrypted = cipherDecrypt.doFinal(encryptedBytes);

    return new String(decrypted);
}

Input Dialog and Display the Input text in a Dialog

// Input Dialog
TextInputDialog dialog = new TextInputDialog("Simon");
dialog.setTitle("Text Input Dialog");
dialog.setHeaderText("Look, a Text Input Dialog");
dialog.setContentText("Please enter your name:");
Optional<String> result = dialog.showAndWait();
System.out.println("Dialog Result: " + result);
Alert alertinputdialog = new Alert(AlertType.INFORMATION);
alertinputdialog.setTitle("Input Result");
alertinputdialog.setHeaderText(null);
if (result.isPresent()) {
    alertinputdialog.setContentText( "Result: " + result.get().toString());
} else {
    alertinputdialog.setContentText("Result: ");
}
alertinputdialog.showAndWait();

Input:

Java Input Box

GUI Output:

Java Dialog

Standard Message Box

// Standard Message Box
Alert alertmessagebox = new Alert(AlertType.INFORMATION);
alertmessagebox.setTitle("Base64 (Style 1/2)");
alertmessagebox.setHeaderText(null);
alertmessagebox.setContentText("About to convert '" + result.get().toString() + "' to Base64");
alertmessagebox.showAndWait();

Output:

Standard Message Box

Detailed Message Box

// Detailed Message Box
Alert alertwarning = new Alert(AlertType.WARNING);
alertwarning.setTitle("Base64 (Style 2/2)");
alertwarning.setHeaderText("About to convert '" + result.get().toString() + "' to Base64");
alertwarning.setContentText("Base64 strings can be reversed");
alertwarning.showAndWait();

GUI Output:

Detailed Java Message Box

Exception Dialog

//Exception Message Box
Alert alertexception = new Alert(AlertType.ERROR);
alertexception.setTitle("Exception Dialog");
alertexception.setHeaderText("Look, an Exception Dialog");
alertexception.setContentText("Could not find file blablah.txt!");
Exception ex = new FileNotFoundException("Could not find file blablah.txt");
// Create expandable Exception.
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String exceptionText = sw.toString();
Label label = new Label("The exception stacktrace was:");
TextArea textArea = new TextArea(exceptionText);
textArea.setEditable(false);
textArea.setWrapText(true);
textArea.setMaxWidth(Double.MAX_VALUE);
textArea.setMaxHeight(Double.MAX_VALUE);
GridPane.setVgrow(textArea, Priority.ALWAYS);
GridPane.setHgrow(textArea, Priority.ALWAYS);
GridPane expContent = new GridPane();
expContent.setMaxWidth(Double.MAX_VALUE);
expContent.add(label, 0, 0);
expContent.add(textArea, 0, 1);
// Set expandable Exception into the dialog pane.
alertexception.getDialogPane().setExpandableContent(expContent);
alertexception.showAndWait();

GUI Output:

Exception dialog with a label textbox, textfield and button.

Close Application

Platform.exit();
System.exit(0);

Close Child Windows

  1. Add Label to the scene (so we can get the parent scene later)
  2. Declare the label in the Controller initialize function ( “public Label lblTitle;”)
  3. Close the stage
Stage stage = (Stage) lblTitle.getScene().getWindow();
stage.close();

Handle Listview Item Select

try{
	DoLog("Selected Server: " + lvwServers.getSelectionModel().getSelectedItem().toString() );
} catch( java.lang.NullPointerException null_error ) {
	return;
}

Open URL in Browser

try {
    Desktop.getDesktop().browse(new URI("https://fearby.com"));
} catch (IOException e1) {
    e1.printStackTrace();
} catch (URISyntaxException e1) {
    e1.printStackTrace();
}

Ask for Input, Add to listview and soft the listview

// Get Parent Stage (use existing label in scene)
Stage stage = (Stage) lblTitle.getScene().getWindow();

// Input Dialog
TextInputDialog dialog = new TextInputDialog("Apple");
dialog.setTitle("Enter a Fruit");
dialog.setHeaderText("Enter a Fruit");
dialog.initOwner(stage.getScene().getWindow());
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.setResizable(Boolean.FALSE);
dialog.setContentText("e.g enter a long description here...");

Optional<String> result = dialog.showAndWait();

if (result.isPresent()) {
    System.out.println( "Fruit: " + result.get());
    lvwFruit.getItems().add(result.get());
} else {
    System.out.println("Result: ");
}

// Sory Listview
lvwFruit.getItems().sorted();

Open FXML Scene File and Modal Child Window

        try {
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("childscene.fxml"));
            Parent root1 = (Parent) fxmlLoader.load();
            Stage stage = new Stage();
            stage.initModality(Modality.APPLICATION_MODAL);
            stage.initStyle(StageStyle.UNDECORATED);
            stage.initStyle((StageStyle.UTILITY));
            stage.setTitle("Child Scene Window Title");
            stage.setScene(new Scene(root1));
            stage.show();
        }
        catch(IOException e) {
            e.printStackTrace();
        }

Base64 Encode and Decode

// Base 64
String sString = result.get().toString();
System.out.println("String sString: " + sString);
try {
    byte[] sbString = sString.getBytes("UTF-8");
    System.out.println("Byte Array - sbString: " + sbString);

    for(byte b : sbString){
        System.out.println(b);
    }
}
catch (Exception ex2)
{
    ex2.printStackTrace();
}
String sbbase64EncodedString = Base64.getEncoder().encodeToString(sString.getBytes());
System.out.println("Base64 Encoded - base64EncodedString: " + sbbase64EncodedString);
byte[] sbbase64DecodedString = Base64.getMimeDecoder().decode(sbbase64EncodedString);
String sbase64DecodedString = new String(sbbase64DecodedString);
System.out.println("Base64 Decoded - sbase64DecodedString: " + sbase64DecodedString);

// Message Box Result of Base64
Alert alertresult = new Alert(AlertType.INFORMATION);
alertresult.setTitle("Base64");
alertresult.setHeaderText("Input String: " + sString);
alertresult.setContentText("Base64 Encoded: " + sbbase64EncodedString + "\nDecoded Base64: " + sbase64DecodedString);
alertresult.showAndWait();

CLI Output:

> Base64 Encoded – base64EncodedString: U2ltb24=
> Base64 Decoded – sbase64DecodedString: Simon

GUI Output:

Message box with base64 text

OK and Cancel Confirmation Box

// MessageBox with Buttons
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirmation Dialog");
alert.setHeaderText("Look, a Confirmation Dialog");
alert.setContentText("Are you ok with this?");

Optional<ButtonType> result2 = alert.showAndWait();
if (result2.get() == ButtonType.OK){
    System.out.println("OK Clicked");
} else {
    System.out.println("Other Clicked");
}

GUI Output:

OK Cancel Dialog Box

Confirmation Box with four options

// Messagebox with many buttons
Alert alertmessaegmanyoptions = new Alert(AlertType.CONFIRMATION);
alertmessaegmanyoptions.setTitle("Confirmation Dialog with Custom Actions");
alertmessaegmanyoptions.setHeaderText("Look, a Confirmation Dialog with Custom Actions");
alertmessaegmanyoptions.setContentText("Choose your option.");
ButtonType buttonTypeOne = new ButtonType("Ubuntu", ButtonData.HELP_2);
ButtonType buttonTypeTwo = new ButtonType("Debian");
ButtonType buttonTypeThree = new ButtonType("Windows");
ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo, buttonTypeThree, buttonTypeCancel);
Optional<ButtonType> result3 = alert.showAndWait();
if (result3.get() == buttonTypeOne){
    System.out.println("Ubuntu Clicked");

} else if (result3.get() == buttonTypeTwo) {
    System.out.println("Debian Clicked");

} else if (result3.get() == buttonTypeThree) {
    System.out.println("Windows Clicked");

} else if (result3.get() == buttonTypeCancel) {
    System.out.println("Cancel Clicked");

} else {
    System.out.println("Nothing Clicked");
}

GUI Output:

Confirmation box with four choices

Encrypt, Base64, AES/CBC/SHA-256 Encryption and Decrypt

fyi: Encrypt and Decrypt functions are above.

String sInputString = result.get().toString();
String sInputStringBas64 = Base64.getEncoder().encodeToString(sInputString.getBytes());
String sEncryptionKey = "pa$w1rd1";

try {
    byte[] encrypted = encrypt(sInputStringBas64, sEncryptionKey);

    String sEncryptedText = new String(encrypted, StandardCharsets.UTF_8);
    System.out.println(sEncryptedText);

    try {
        String sDecryptedText = decrypt(encrypted, sEncryptionKey);
        System.out.println("decrypted: " + sDecryptedText);

        byte[] sbbase64EncryptedDecodedString = Base64.getMimeDecoder().decode(sDecryptedText);
        String sbase64EncryptedDecodedString = new String(sbbase64EncryptedDecodedString);

        // Encryption Message Box
        Alert encryptionmessagebox = new Alert(AlertType.INFORMATION);
        encryptionmessagebox.setTitle("Encryption");
        encryptionmessagebox.setHeaderText(null);
        encryptionmessagebox.setContentText("Input String:\n" + sInputString
                        + "\n\n  Input as Base64:\n   " + sInputStringBas64
                        + "\n\n  Encryption Key:\n  " + sEncryptionKey
                        + "\n\n  Encryption Method:\n  AES/CBC/PKCS5Padding SHA-256 IV"
                        + "\n\n    Encrypted Text:\n    " + sEncryptedText
                        + "\n\n  Decrypted Text:\n  " + sDecryptedText
                        + "\n\nDecoded Base64:\n" + sbase64EncryptedDecodedString
        );
        encryptionmessagebox.showAndWait();
    }
    catch (Exception ee)
    {
        ee.printStackTrace();
    }
}
catch (Exception ex2)
    {
        ex2.printStackTrace();
    }

GUI Output:

Encrypt and decrypt

Credits 

Encryption Help: https://proandroiddev.com/security-best-practices-symmetric-encryption-with-aes-in-java-7616beaaade9

Dialogue Help: https://code.makery.ch/blog/javafx-dialogs-official/

General JavaFX Help: http://tutorials.jenkov.com/javafx/index.html

Ini File Help: Simple Java API Windows style .ini file handling. Also provide Java Preferences API
functionality on top of .ini file. https://sourceforge.net/projects/ini4j/

SSH JScH Help – JSch is a pure Java implementation of SSH2: http://www.jcraft.com/jsch/

JSch 0.0.* was released under the GNU LGPL license. Later, we have switched
over to a BSD-style license.

——————————————————————————
Copyright (c) 2002-2015 Atsuhiko Yamanaka, JCraft,Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.

3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
——————————————————————————

——————————————————————————

I hope this guide helps someone.

Please consider using my referral code and get $25 UpCloud VM credit if you need to create a server online.

https://www.upcloud.com/register/?promo=D84793

Ask a question or recommend an article

[contact-form-7 id=”30″ title=”Ask a Question”]

Revision History

v1.0 Initial Post

Filed Under: Code, Java Tagged With: code, java, jdx

Creating your first Java FX app and using the Gluon Scene Builder in the IntelliJ IDEA IDE

July 3, 2018 by Simon

This is quick guide explaining how I created my first JavaFX application using the Gluon Scene Builder in the IntelliJ IDEA IDE.

I have a number of guides on moving away from CPanel, Setting up VM’s on UpCloud, AWS, Vultr or Digital Ocean along with installing and managing WordPress from the command line. I created this blog post on creating a Java GUI app with the older Swing technology (Java FX replaces Swing). I now want to create a JavaFX app to control my UpCloud VM’s.

If you have not read my previous posts I have now moved my blog etc to the awesome UpCloud host. Sign up using this link to get $25 free credit.

Do read: Preparing for JavaFX Application Development: https://wiki.openjdk.java.net/display/OpenJFX/Building+OpenJFX#BuildingOpenJFX-Mac

Downloading Java

Download and install Java SE 8 or higher from http://www.oracle.com/technetwork/java/javase/downloads/index.html

Java 10 install screenshot

Download Intelli J IDEA IDE

Goto https://www.jetbrains.com/idea/

Click Download

Intelli J IDEA from www.jetbrains.com

Download the community edition

IntelliJ Download Options (Ultimate or Community)

Install Intelli J IDEA IDE

Drag Intelli J to your applications folder

Install Scenebuilder

I downloaded the Java Scene Builder (1.1 or 2.0) from here.

Download Scene Scene Builder

Install the Scene Builder (open the installer and drag it to your applications folder).

Configure the Scene Builder in IntelliJ IDEA IDE

  1. Open Intelli J IDEA IDE (set the default’s you wish)
  2. Create a New Project
  3. Open Intelli J IDEA IDE Preferences
  4. Open Languages & Frameworks then JavaFX and set your Scene Builder path (e.g /Applications/JavaFX Scene Builder 2.0.app/)
  5. Exit Preferences

Set the Scene Builder Path in IntelliJ

You can now create a JavaFX project an have a workign scene builder GUI.

New Project

After you create a JavaFX project open your JavaFX fxml file in Scene Builder (right click on the .fxml file and select Open in Scene Builder)

Scene Builder

Extended Scene Builder from Gluon

I read that there is a better Scene builder GUI available from https://gluonhq.com/products/scene-builder/

Read some of the Java Scene Builder v Gluon Scene Builder history here at Reddit for the latest on why.

I am going to download the Gluon Scene Builder from http://gluonhq.com/products/scene-builder/

Gluon Scene Builder webpage screenshot of https://gluonhq.com/products/scene-builder/

Download and install the Gluon Scene builder (at the time of writing requires Java 9 or higher).

Drag the scene builder to your apps folder to install

Now open IntelliJ IDEA IDE and open the preferences and change the scene builder path from “/Applications/JavaFX Scene Builder 2.0.app/” to “/Applications/SceneBuilder.app/“.

Save the IntelliJ IDEA preferences and Right click on your projects “fxml” file again and click “Open In Scene Builder” , do verify it is indeed the Gluon Scene builder by opening the about menu.

Gluon Scene Builder Help Menu Screenshot

Designing your first JavaFX app

Now you can design and code a JavaFX application with Gluon Scene Builder.

I am not an expert at java apps so i’d highly recommend you follow this guide to learn how to build a well-structured JavaFX panel layout (just ignore that it is using the standard Scene Builder, it works with the gluon one).

You should now have a working Java FX App

Java FX App running

The scene builder will save changes to your fxml file

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.TreeView?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.Region?>
<?import javafx.scene.layout.VBox?>


<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/9.0.4" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <top>
      <VBox BorderPane.alignment="CENTER">
         <children>
            <MenuBar>
              <menus>
                <Menu mnemonicParsing="false" text="File">
                  <items>
                    <MenuItem mnemonicParsing="false" text="Close" />
                  </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Edit">
                  <items>
                    <MenuItem mnemonicParsing="false" text="Delete" />
                  </items>
                </Menu>
                <Menu mnemonicParsing="false" text="Help">
                  <items>
                    <MenuItem mnemonicParsing="false" text="About" />
                  </items>
                </Menu>
              </menus>
            </MenuBar>
            <HBox spacing="8.0">
               <children>
                  <TextField promptText="ip" />
                  <TextField promptText="Username" />
                  <TextField promptText="Password" />
                  <Button mnemonicParsing="false" onMouseClicked="#loginButtonClicked" prefHeight="27.0" prefWidth="68.0" text="Login" />
                  <Region HBox.hgrow="ALWAYS" />
                  <Button mnemonicParsing="false" onMouseClicked="#settingsButtonClicked" text="Settings" />
               </children>
               <padding>
                  <Insets bottom="8.0" left="8.0" right="8.0" top="8.0" />
               </padding>
            </HBox>
         </children>
      </VBox>
   </top>
   <left>
      <TreeView prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
   </left>
   <center>
      <TextArea prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
   </center>
   <bottom>
      <HBox BorderPane.alignment="CENTER">
         <children>
            <Label text="Label" />
         </children>
         <padding>
            <Insets bottom="2.0" left="2.0" right="2.0" top="2.0" />
         </padding>
      </HBox>
   </bottom>
</BorderPane>

You can add functions into your controller class

package sample;

public class Controller {

    public void loginButtonClicked(){
        System.out.println("Login");

    }

    public void settingsButtonClicked(){
        System.out.println("Settings");

    }

}

Instaling Gluon JavaFX Templates

Close your test project and create a new project, but before you do click Configure then Plugins

Gluon has some nice templates

Now lets open In the following screen click Browse Repositories.

Search the repository for and install the “Gluon” plugin

Install Gluon Plugin

Restart IntelliJ IDEA IDE then you can use templates when creating a project.

Get your own VM

If you have not read my previous posts I have now moved my blog etc to the awesome UpCloud host. Sign up using this link to get $25 free credit.

Packaging a Java app for distribution on OSX

I will show how you can package your app to run on a Mac by using this.

Coming Soon

I will add more guides soon on using a custom JavaFx app to allow you to manage your own UpCloud server and perform Deploy/Init/Setup/Configure/Operate actions. Running CLI commands to deploy and manage a server is fun but is very tedious.

I blogged recently about using the UpCloud API and setting up a subdomain recently (I will use this server to test and prove the Javmanagementnt app).

Links

  • Official Javafx examples
  • Official Java learning paths.
  • Javafx examples at javacodegeeks.com
  • Java widgets
  • Reddit JavaHelp
  • Jenkov Tutorials

I hope this guide helps someone.

Ask a question or recommend an article

[contact-form-7 id=”30″ title=”Ask a Question”]

Revision History

V1.6 Jenkov Tutorials

V1.5 Reddit java help

V1.4 added java widgets link

V1.3 added javafx examples link.

V1.2 added Java learning paths

V1.1 added official Javafx examples

v1.0 Initial post

Filed Under: Development, IDE, Java Tagged With: and, app, Builder, creating, first, FX, Gluon, ide, idea, in, IntelliJ, java, Scene, the, Using, your

Write your first Java GUI app

March 31, 2018 by Simon

Here is a quick guide that shows how you can create and compile your first Java app with Net Beans.

I have a number of guides on moving hasting away form CPanel, Setting up VM’s on AWS, Vultr or Digital Ocean along with installing and managing WordPress from the command line. Updating the serves is a pain so I am writing a java app for Windows and OSX to help me manage the server by telnetting in on port 22 and performing routine actions from a button click in Java.

Installing Java and NetBeans IDE

Go to https://netbeans.org/downloads/index.html and click “JDK with NetBeans IDE Java SE bundle”

Download Net Beans

Download Netbeans and Java SE bundle

Download

Install Netbeans and Java SE bundle

Installed

Creating your first GUI Java Application

Create  New Project (Java Application) in NetBeans, Click Next

New Project

Name the project and set the main class as “main”

New Project

Add a new file, a “Swing GUI Form/JFrame form“.

Add Form

Name the J Frame Form and click Finish.

J Frame Form

Adding GUI elements in NetBeans IDE

In the Net Beans IDE, you can simply drag and drop elements.  I like to move my properties screen to the bottom centre.

GUI Designer

Set the panel at the default startup element

Add the following code to the main.java file

> framemain form = new framemain();
> form.setVisible(true);

Show Form

Compile the App

The app compiles 🙂

App Compiles

Add an action to a button

You can add button actions (events) in the design mode.

Add Button Event

Add Hello World alert box code to the button

Add the following to the Panel code file

> public static void infoBox(String infoMessage, String titleBar)
> {
>     JOptionPane.showMessageDialog(null, infoMessage, “InfoBox: ” + titleBar, JOptionPane.INFORMATION_MESSAGE);
> }

Add this to the action (event)

System.out.println(“Hello World”);
> frame1.infoBox(“Hello World”, “Hello World”);

Build

To build right-click on the project and click Clean and Build

java-build

The result is an app you can run by double-clicking the jar file.

Java Hello World Alert Box

I hope this helps someone.

Making an OSX APP file from the JAR file

Coming soon

Making a Windows EXE file from the JAR file

Coming soon

I hope this guide helps someone.

Ask a question or recommend an article

[contact-form-7 id=”30″ title=”Ask a Question”]

Revision History

v1.0 Initial post

Filed Under: Java Tagged With: app, first, gui, java, Write, your

Primary Sidebar

Poll

What would you like to see more posts about?
Results

Support this Blog

Create your own server today (support me by using these links

Create your own server on UpCloud here ($25 free credit).

Create your own server on Vultr here.

Create your own server on Digital Ocean here ($10 free credit).

Remember you can install the Runcloud server management dashboard here if you need DevOps help.

Advertisement:

Tags

2FA (9) Advice (17) Analytics (9) App (9) Apple (10) AWS (9) Backup (21) Business (8) CDN (8) Cloud (49) Cloudflare (8) Code (8) Development (26) Digital Ocean (13) DNS (11) Domain (27) Firewall (12) Git (7) Hosting (18) IoT (9) LetsEncrypt (7) Linux (21) Marketing (11) MySQL (24) NGINX (11) NodeJS (11) OS (10) Performance (6) PHP (13) Scalability (12) Scalable (14) Security (45) SEO (7) Server (26) Software (7) SSH (7) ssl (17) Tech Advice (9) Ubuntu (39) Uncategorized (23) UpCloud (12) VM (45) Vultr (24) Website (14) Wordpress (25)

Disclaimer

Terms And Conditions Of Use All content provided on this "www.fearby.com" blog is for informational purposes only. Views are his own and not his employers. The owner of this blog makes no representations as to the accuracy or completeness of any information on this site or found by following any link on this site. Never make changes to a live site without backing it up first.

Advertisement:

Footer

Popular

  • Backing up your computer automatically with BackBlaze software (no data limit)
  • How to back up an iPhone (including photos and videos) multiple ways
  • Add two factor auth login protection to WordPress with YubiCo hardware YubiKeys and or 2FA Authenticator App
  • Setup two factor authenticator protection at login on Ubuntu or Debian
  • Using the Yubico YubiKey NEO hardware-based two-factor authentication device to improve authentication and logins to OSX and software
  • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
  • Monitor server performance with NixStats and receive alerts by SMS, Push, Email, Telegram etc
  • Speeding up WordPress with the ewww.io ExactDN CDN and Image Compression Plugin
  • Add Google AdWords to your WordPress blog

Security

  • Check the compatibility of your WordPress theme and plugin code with PHP Compatibility Checker
  • Add two factor auth login protection to WordPress with YubiCo hardware YubiKeys and or 2FA Authenticator App
  • Setup two factor authenticator protection at login on Ubuntu or Debian
  • Using the Yubico YubiKey NEO hardware-based two-factor authentication device to improve authentication and logins to OSX and software
  • Setting up DNSSEC on a Namecheap domain hosted on UpCloud using CloudFlare
  • Set up Feature-Policy, Referrer-Policy and Content Security Policy headers in Nginx
  • Securing Google G Suite email by setting up SPF, DKIM and DMARC with Cloudflare
  • Enabling TLS 1.3 SSL on a NGINX Website (Ubuntu 16.04 server) that is using Cloudflare
  • Using the Qualys FreeScan Scanner to test your website for online vulnerabilities
  • Beyond SSL with Content Security Policy, Public Key Pinning etc
  • Upgraded to Wordfence Premium to get real-time login defence, malware scanner and two-factor authentication for WordPress logins
  • Run an Ubuntu VM system audit with Lynis
  • Securing Ubuntu in the cloud
  • No matter what server-provider you are using I strongly recommend you have a hot spare ready on a different provider

Code

  • How to code PHP on your localhost and deploy to the cloud via SFTP with PHPStorm by Jet Brains
  • Useful Java FX Code I use in a project using IntelliJ IDEA and jdk1.8.0_161.jdk
  • No matter what server-provider you are using I strongly recommend you have a hot spare ready on a different provider
  • How to setup PHP FPM on demand child workers in PHP 7.x to increase website traffic
  • Installing Android Studio 3 and creating your first Kotlin Android App
  • PHP 7 code to send object oriented sanitised input data via bound parameters to a MYSQL database
  • How to use Sublime Text editor locally to edit code files on a remote server via SSH
  • Creating your first Java FX app and using the Gluon Scene Builder in the IntelliJ IDEA IDE
  • Deploying nodejs apps in the background and monitoring them with PM2 from keymetrics.io

Tech

  • Backing up your computer automatically with BackBlaze software (no data limit)
  • How to back up an iPhone (including photos and videos) multiple ways
  • US v Huawei: The battle for 5G
  • Check the compatibility of your WordPress theme and plugin code with PHP Compatibility Checker
  • Is OSX Mojave on a 2014 MacBook Pro slower or faster than High Sierra
  • Telstra promised Fibre to the house (FTTP) when I had FTTN and this is what happened..
  • The case of the overheating Mac Book Pro and Occam’s Razor
  • Useful Linux Terminal Commands
  • Useful OSX Terminal Commands
  • Useful Linux Terminal Commands
  • What is the difference between 2D, 3D, 360 Video, AR, AR2D, AR3D, MR, VR and HR?
  • Application scalability on a budget (my journey)
  • Monitor server performance with NixStats and receive alerts by SMS, Push, Email, Telegram etc
  • Why I will never buy a new Apple Laptop until they fix the hardware cooling issues.

Wordpress

  • Replacing Google Analytics with Piwik/Matomo for a locally hosted privacy focused open source analytics solution
  • Setting web push notifications in WordPress with OneSignal
  • Telstra promised Fibre to the house (FTTP) when I had FTTN and this is what happened..
  • Check the compatibility of your WordPress theme and plugin code with PHP Compatibility Checker
  • Add two factor auth login protection to WordPress with YubiCo hardware YubiKeys and or 2FA Authenticator App
  • Monitor server performance with NixStats and receive alerts by SMS, Push, Email, Telegram etc
  • Upgraded to Wordfence Premium to get real-time login defence, malware scanner and two-factor authentication for WordPress logins
  • Wordfence Security Plugin for WordPress
  • Speeding up WordPress with the ewww.io ExactDN CDN and Image Compression Plugin
  • Installing and managing WordPress with WP-CLI from the command line on Ubuntu
  • Moving WordPress to a new self managed server away from CPanel
  • Moving WordPress to a new self managed server away from CPanel

General

  • Backing up your computer automatically with BackBlaze software (no data limit)
  • How to back up an iPhone (including photos and videos) multiple ways
  • US v Huawei: The battle for 5G
  • Using the WinSCP Client on Windows to transfer files to and from a Linux server over SFTP
  • Connecting to a server via SSH with Putty
  • Setting web push notifications in WordPress with OneSignal
  • Infographic: So you have an idea for an app
  • Restoring lost files on a Windows FAT, FAT32, NTFS or Linux EXT, Linux XFS volume with iRecover from diydatarecovery.nl
  • Building faster web apps with google tools and exceed user expectations
  • Why I will never buy a new Apple Laptop until they fix the hardware cooling issues.
  • Telstra promised Fibre to the house (FTTP) when I had FTTN and this is what happened..

Copyright © 2023 · News Pro on Genesis Framework · WordPress · Log in

Some ads on this site use cookies. You can opt-out if of local analytics tracking by scrolling to the bottom of the front page or any article and clicking "You are not opted out. Click here to opt out.". Accept Reject Read More
GDPR, Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT