Showing posts with label Java SE. Show all posts
Showing posts with label Java SE. Show all posts

May 27, 2020

Update JavaFX GUI Periodically (e.g. every second)

If you want to periodically display new data in your GUI, then you could use "Timeline" (all classes from the javafx.*-packages), e.g. for updating every 1.0 second:


Timeline timeline = new Timeline(
    new KeyFrame(Duration.seconds(1.0), e -> {
        /*
         * read new data and update GUI nodes here ...
         */
    })
);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();


If you use FXML, a good point to call this piece of code would be in your FXML controller class:


public class ControllerForFXML implements Initializable {

    @Override
    void initialize(URL location, ResourceBundle resources) {
        /*
         * Timeline code from above here ...
         */
    }
}

Apr 4, 2017

Read and Write a File Line by Line in Java 8

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public class FileTest {

 public static void main(String[] args) throws IOException  {
  
  Path pathToRead = Paths.get("C:\\...\\dataIn.csv");
  
  // Check if file exists
  if(!Files.exists(pathToRead)) {
   System.out.println("file doesn't exist :-(");
   return;
  };
  
  // read a file line by line
  Files.lines(pathToRead).forEach(line -> {
   // Process the String line here!!
   System.out.println(line);
  });
  
  // write a file line by line
  List<String> lines = Arrays.asList("line 1", "line 2", "line 3");
  Path pathToWrite = Paths.get("C:\\...\\dataOut.csv");
  Files.write(pathToWrite, lines);
 }
}

In Files.write() you can use also add Options, e.g. StandardOpenOption.CREATE or StandardOpenOption.APPEND. If omitted like above you get StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING.

More options to read/write also larger files in a buffered way are found here https://www.baeldung.com/java-read-file

Sep 24, 2015

Recursive search in a non-binary tree in TreeView of JavaFX

Search for a node in a non-binary tree (any node can have multiple children 0-n) and exit from recursion immediately, when the first hit is found. We give an example with the search of a TreeItem with a given name in a TreeView of JavaFX, which can be easily adapted to any tree like structure:

TreeItem<String> searchTreeItem(TreeItem<String> item, String name) {
		
	if(item.getValue().equals(name)) return item; // hit!

	// continue on the children:
	TreeItem<String> result = null;
	for(TreeItem<String> child : item.getChildren()){
		 result = searchTreeItem(child, name);
		 if(result != null) return result; // hit!
	}
	
	//no hit:
	return null;
}

If you want to search the whole tree treeView for a node with name "bigdev", just pass in the root:

TreeItem<String> result = searchTreeItem(treeView.getRoot(), "bigdev");

Mar 31, 2014

Tutorial: Installing Eclipse with e(fx)clipse and Scene Builder for JavaFX

For e(fx)clipse you have two possibilites:
OR
  1. As a prerequisite install Xtext & Xtend 2.5.1 on Eclipse:  Help > Install new software... > work with: http://download.eclipse.org/modeling/tmf/xtext/updates/composite/releases/
  2. Install e(fx)clipse: http://www.eclipse.org/efxclipse/install.html (e.g. for version 0.9.0: Help > Install new software... > work with: http://download.eclipse.org/efxclipse/updates-released/0.9.0/site, check the Kepler-version)
  3. Install Scene Builder: http://www.oracle.com/technetwork/java/javase/downloads/javafxscenebuilder-info-2157684.html


Mar 20, 2014

Tutorial: Installing JDK 7 and Eclipse Kepler SR2

There are two steps required:
  1. Download and install a JDK version 7 (Java Development Kit) 
  2. Download Eclipse IDE (same bit version as for the JRE, i.e. 32 or 64 bit) and unzip

Tutorial: Installing Eclipse with JDK on USB Flash Drive / Stick

If you work on different computers, but want to have the same dev environment, just create a mobile version on an USB flash drive:
  1. Download Eclipse and unzip on your USB drive, e.g. "X:\eclipse" 
  2. Install a JDK on your computer (e.g. to "C:\Programme\Java\jdk1.7.xx")
  3. Copy "C:\Programme\Java\jdk1.7.x" to "X:\Java\jdk1.7.xx" j
  4. Paste into the file "X:\eclipse\eclipse.ini" just before "-vmargs"
  5.     -vm
        ..\Java\jdk1.7.xx\bin\javaw
  6. Start Eclipse with "X:\Eclipse\eclipse.exe" 
  7. Set the workspace to ".\workspace" (relative path!)
Done!

Mar 19, 2014

Tutorial: Installing Java 8 support for Eclipse Kepler

Java SE 8 has launched (http://www.oracle.com/technetwork/java/javase/downloads/index.html), but what about support in Eclipse Kepler? There is a feature patch (https://wiki.eclipse.org/JDT_Core/Java8), but only for Kepler SR2 (4.3.2). 

Installation (https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler):

  1. Help > Install New Software...
  2. enter the following URL into the 'Work with' field: http://download.eclipse.org/eclipse/updates/4.3-P-builds/
  3. select category 'Eclipse Java 8 Support (for Kepler SR2)'
  4. for faster install, deselect 'Contact all updates sites during install to find required software'
  5. click 'Next', click 'Next', accept the license, click 'Finish', restart Eclipse when asked...

Feb 14, 2014

GUI Design Patterns: MVC, MVP vs. MVVM

There are three famous GUI Design Patterns:
  • MVC: Model - View - Controller (e.g. ASP.NET, Java Swing and JavaFX, JSF)
  • MVP: Model - View - Presenter (e.g. WinForms, Java Swing and JavaFX, see Martin Fowler on GUI Architectures and the Presentation Model)
  • MVVM: Model - View - ViewModel (e.g. .NET WPF, Knockout JavaScript, JavaFX)
These GUI design patterns try to achieve
  • Modularity / Loose Coupling (through "separation of duties/concerns" and dependency injection)
  • Testability (test the different components independently)
  • Maintainability (e.g. changes can be made in one component without touching the others)

What's in common?
  • View: responsible for presentation in GUI (GUI components like buttons, labels etc. and layout & styling)
  • Model: data and behavior (domain objects and logic, services for database interaction)
  • Controller / Presenter / ViewModel: responsible for separation of the latter two (glue logic!)

What's different?

The associations between the three! (see the picture below) First of all, the MVVM pattern is just a specialization of the MVP, that is more loosely coupled through the concept of data binding.
The difference between MVP/MVVM and MVC is, that the View and the Model are completely decoupled - that's a good thing :-)
The black arrows represent a direct association, the red dotted arrows an indirect association (e.g. Observer Pattern/Events/Data Binding)


A good talk explaining this is "MVC,MVP and MVVM: A Comparison of Architectural Patterns" by Joseph Homnick:



Jun 14, 2013

Getting JDBC SQL Connection in JPA with Hibernate

When you need to retrieve the plain Connection from JPA, unfortunately, there is no JPA standard way (unless you get a configured datasource with JNDI). This is needed when you use libraries or legacy applications which use JDBC instead of JPA.


Hibernate 3.x and JPA 1.0

With Hibernate you can get the org.hibernate.session. In pre Hibernate 4.o there was the connection() method which now is removed.
EntityManager em = ...;
Session session = (Session) em.getDelegate();
Connection conn = session.connection();

Hibernate 3.x and JPA 2.0

EntityManager em = ...;
Connection conn = em.unwrap(Session.class).connection();

Hibernate 4.x and JPA 2.0

Session session = em.unwrap(Session.class);
SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
ConnectionProvider cp = sfi.getConnectionProvider();
Connection conn = cp.getConnection();

JNDI-Lookup

If you are running inside a container, you could also perform a JNDI lookup on the configured DataSource.

May 1, 2013

MOOC: Introduction to Programming (Java)

Wave Learn programming with Java from Cay Horstmann, Cheng-Han Lee and Sara Tansey of the San José State University in the MOOC at Udacity:


starting Jun 3rd 2013.

Apr 24, 2013

Tutorial: Determinant of a Matrix in Java

Calculating the determinant of a quadratic matrix A=(a_ij) of size n using Laplace's formula with expanding along the i-th row is given by
where A_ij is the so-called minor (it is A with the i-th row and j-th column removed). Note that it is a recursive definition; it terminates since the size of the matrices decreases and the determinant of a number is the number itself.

In Java it can be implemented like this (for i=1, i.e. the first row):

package de.bigdev;

public class Determinant {

    /**
     * Determinant of a matrix using Laplace's formula with expanding along the
     * 0th row. It is not checked whether the matrix is quadratic!
     * 
     * @param m Matrix
     * @return determinant
     */
    public static double det(double[][] m) {
        int n = m.length;
        if (n == 1) {
            return m[0][0];
        } else {
            double det = 0;
            for (int j = 0; j < n; j++) {
                det += Math.pow(-1, j) * m[0][j] * det(minor(m, 0, j));
            }
            return det;
        }
    }

    /**
     * Computing the minor of the matrix m without the i-th row and the j-th
     * column
     * 
     * @param m input matrix
     * @param i removing the i-th row of m
     * @param j removing the j-th column of m
     * @return minor of m
     */
    private static double[][] minor(final double[][] m, final int i, final int j) {
        int n = m.length;
        double[][] minor = new double[n-1][n-1];
        // index for minor matrix position:
        int r = 0, s = 0;
        for (int k = 0; k < n; k++) {
            double[] row = m[k];
            if (k != i) {
                for (int l = 0; l < row.length; l++) {
                    if (l != j) {
                        minor[r][s++] = row[l];
                    }
                }
                r++;
                s = 0;
            }
        }
        return minor;
    }

    private static void printMatrix(double[][] m) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < m.length; i++) {
            double[] row = m[i];
            sb.append("[");
            for (int j = 0; j < row.length; j++) {
                sb.append(" ");
                sb.append(row[j]);
            }
            sb.append(" ]\n");
        }
        sb.deleteCharAt(sb.length() - 1);

        System.out.println(sb.toString());
    }

    public static void main(String[] args) {

        System.out.println("Determinant");
        System.out.println("===========");
        
        double[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 0 } };
        double[][] b = { { 1 } };
        double[][] c = { { 1, 2 }, { 3, 4 } };
        
        System.out.println("");
        System.out.println("Testing minor");
        System.out.println("=============");
        printMatrix(a);
        System.out.println("deleting row 3, and column 2:");
        printMatrix(minor(a, 2, 1));

        System.out.println("");
        System.out.println("Testing det");
        System.out.println("===========");
        
        printMatrix(b);
        System.out.println("has det=" + det(b) +"\n");
        
        printMatrix(c);
        System.out.println("has det=" + det(c) +"\n");
        
        printMatrix(a);
        System.out.println("has det=" + det(a) +"\n");
    }
}

You get following output on the console:


Determinant
===========

Testing minor
=============
[ 1.0 2.0 3.0 ]
[ 4.0 5.0 6.0 ]
[ 7.0 8.0 0.0 ]
deleting row 3, and column 2:
[ 1.0 3.0 ]
[ 4.0 6.0 ]

Testing det
===========
[ 1.0 ]
has det=1.0

[ 1.0 2.0 ]
[ 3.0 4.0 ]
has det=-2.0

[ 1.0 2.0 3.0 ]
[ 4.0 5.0 6.0 ]
[ 7.0 8.0 0.0 ]
has det=27.0

Apr 5, 2013

Hello World and 99 Bottles of Beer

Didn't know that there were so many...

Apr 4, 2013

OOP Tutorial: 2-dimensional Vector as Java Object

When starting to learn object orientated programming, a good first example is the following: Modelling a 2-dimensional vector over the real numbers could result in this

package de.bigdev;

public class Vector {

    private double x;
    private double y;

    public Vector(double x, double y) {
        super();
        this.x = x;
        this.y = y;
    }
    
    /**
     * Addition of two vectors
     *
     * @param v
     * @return the sum with v
     */
    public Vector add(Vector v) {
        return new Vector(x + v.x, y + v.y);
    }
    
    /**
     * Scalar Mulitplication with a constant
     *
     * @param c
     * @return the scalar multiplication with c
     */
    public Vector scalarMult(double c) {
        return new Vector(c * x, c * y);
    }

    /**
     * Length of two vectors
     * 
     * @return length
     */
    public double length() {
        return Math.sqrt(x * x + y * y);
    }

    /**
     * Scalar Product of two vectors
     * 
     * @param v
     * @return the scalar product with v
     */
    public double scalarProd(Vector v) {
        return this.x * v.getX() + this.y * v.getY();
    }

    /**
     * Angle between two vectors
     * 
     * @param v
     * @return the angle with v in degrees
     */
    public double angle(Vector v) {
        return Math.acos(this.scalarProd(v) / (this.length() * v.length()))
                * 180.0 / Math.PI;
    }

    public double getX() { return x; }
    public double getY() { return y; }

    @Override
    public String toString() {
        return "[" + x + ", " + y + "]";
    }

    /**
     * for testing only. should be factored out into another class... or use
     * JUnit!
     * 
     * @param args
     */
    public static void main(String[] args) {
        Vector v = new Vector(1, 1);
        Vector w = new Vector(-1, -1);

        System.out.println("Vector algebra");
        System.out.println("==============");
        System.out.println("addition      : " + v + " + " + w + " = " + v.add(w));
        System.out.println("scalar multip.: 2 * " + v + " = " + v.scalarMult(2));
        System.out.println("length        : ||" +v + "|| = " + v.length());
        System.out.println("scalar product: " + v + " * " + w + " = " + v.scalarProd(w));
        System.out.println("angle         : angle(" + v + ", " + w
          + ") = " + Math.round(v.angle(w)) + "°");
    }
}

The output on the console is


Vector algebra
==============
addition      : [1.0, 1.0] + [-1.0, -1.0] = [0.0, 0.0]
scalar multip.: 2 * [1.0, 1.0] = [2.0, 2.0]
length        : ||[1.0, 1.0]|| = 1.4142135623730951
scalar product: [1.0, 1.0] * [-1.0, -1.0] = -2.0
angle         : angle([1.0, 1.0], [-1.0, -1.0]) = 180°


Dec 6, 2012

Getting motivated: Code Hard


Lyrics

In the cubicles representin’ for my JAVA homies… In by nine, out when the deadlines are met, check it.

We code hard in these cubicles. My style’s nerd-chic, I’m a programmin’ freak.
We code hard in these cubicles. Only two hours to your deadline? Don’t sweat my technique.
Sippin’ morning coffee with that JAVA swirl. Born to code; my first words were “Hello World”
Since 95, been JAVA codin’ stayin’ proud. Started on floppy disks, now we take it to the cloud.
On my desktop, JAVA’s what’s bobbin’ and weavin’. We got another winning app before I get to OddEven.
Blazin’ code like a forest fire, climbin’ a tree. Setting standards like I Triple E….
Boot it on up, I use the force like Luke. Got so much love for my homeboy Duke.
GNU Public Licensed, it’s open source. Stop by my desk when you need a crash course
Written once and my script runs anywhere. Straight thuggin’, mean muggin’ in my Aeron chair.
All the best lines of code, you know I wrote ‘em. I’ll run you out of town on your dial-up modem.

‘Cause… We code hard in these cubicles. Me and my crew code hyphy hardcore.
We code hard in these cubicles. It’s been more than 10 years since I’ve seen the 404.
Inheriting a project can make me go beeee-serk. Ain’t got four hours to transfer their Framework.
The cleaners killed the lights, Man, that ain’t nice. Gonna knock this program out, just like Kimbo Slice
I program all night, just like a champ. Look alive under this IKEA lamp.
I code HARDER in the midnight hour, E7 on the vending machine fuels my power.
Ps3 to Smartphones, our code use never ends. JAVA’s there when I beat you in “Words with Friends”.
My developing skills are so fresh please discuss. You better step your game up on that C++.
We know better than to use Dot N-E-T. Even Dan Brown can’t code as hard as me.
You know JAVA’s gettin’ bigger, that’s a promise not a threat. Let me code it on your brain
so you’ll never forget.

We code hard in these cubicles, it’s the core component…of what we implement.
We code hard in these cubicles. Straight to your JAVA Runtime Environment.
We code hard in these cubicles. Keep the syntax light and the algorithm tight.
We code hard in these cubicles. Gotta use JAVA if it’s gonna run right.
We code hard in these cubicles. JAVA keeps adapting, you know it’s built to last.
We code hard in these cubicles. Robust and secure, so our swag’s on blast
CODE HARD

Nov 19, 2012

First Post!

Just testing if the SyntaxHighlighter for highlighting code works:

System.out.println("Hello bigDev.de!");

Yes it does! For integration with Blogger see here! I used the <pre class="brush:xxx">-tag which has some problems with html: you should escape the html characters, e.g. with QuickEscape.