Java Examples

Prompt user for console input and validate their response

Java 6.12.2015 No Comments

We often get students struggling to read and validate console input from the user. The following example gives a simple example of an approach that can be used. It reads the input from the user and checks if it is a valid double. If its not it prompts the user again. Could easily be modified…

Read More

Printing Triangles in Java

Featured, Java 23.11.2015 1 Comment

A common problem many new Java developers is to write a program that prints out a triangle. There a lots of variations on this problem but lets start with a simple case and then have a look at some possible variations. Probably the simplest case is a left aligned triangle of stars that looks like…

Read More

How do I get a JScrollPane to always display scroll bars?

Java, Swing, Tip 6.11.2015 No Comments

You can achieve this by setting the scroll bar policy on both the verical and horizontal scroll bars.

Read More

How to control decimal places displayed in JTable column?

Java, Swing 10.9.2015 1 Comment

Rendering of table cells is handled by instances of TableCellRenderer. By default JTable uses a DefaultTableCellRenderer to render all of its cells. To control the number of decimal places used we just need to subclass DefaultTableCellRenderer and format the cell double value before passing the (formatted) value to to the parent (DefaultTableCellRenderer) class. To get…

Read More

How to copy a file using Java 6

Java, Tip 10.7.2015 No Comments

Prior to Java 7, Java did not provide a standard method to copy a file. To implement copying you needed to read all bytes from source file and write to destination. The read() method will return -1 when eof is reached, otherwise it returns the number of bytes read.

Read More