Saturday, November 30, 2013

Run Netbeans generated jar of Java program as stand alone program and create desktop shortcut

To run Netbeans generated jar in Windows cmd prompt:

Click Run > Clean and Build Project. In Output window wil show you how to run this application from the command line without Ant.


You can open cmd prompt and copy the command to run it as stand alone program.


Related:
Run the Nerbeans generated jar of JavaFX application as stand alone program

Run the Nerbeans generated jar of JavaFX application as stand alone program

To run the jar generated by Netbeans IDE, we have to locate the target folder. Click Run in Netbeans IDE > Clean and Build Project. Once BUILD SUCCESSFUL, the Created dir will be shown on Output window.


Open File Manager and open the created dir. You can find a Executable Jar file.


You can run it by double clicking. And also you can create desktop shortcut of it.



Related: - Run Netbeans generated jar of Java program as stand alone program and create desktop shortcut

Tuesday, November 19, 2013

Read text file with InputStream of getClass().getResourceAsStream()

This example show how to read text from InputStream of getClass().getResourceAsStream(src). Where src is the text file inside package.


package java_readfile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_ReadFile {

    String src = "song.txt";

    public static void main(String[] args) {

        Java_ReadFile java_ReadFile = new Java_ReadFile();
        java_ReadFile.readFile();
    }

    private void readFile() {
        StringBuilder stringBuilder = new StringBuilder();

        InputStream inputStream = getClass().getResourceAsStream(src);

        if (inputStream == null) {
            System.out.println("inputStream == null");
        } else {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            
            try {
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                System.out.print(stringBuilder.toString());
            } catch (IOException ex) {
                Logger.getLogger(Java_ReadFile.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        System.out.println("- Finish -");
    }
}

Get user home and java home with Java code

To get user home and java home, call System.getProperty() method with parameter of "user.home" or "java.home".

user home and java home
user home and java home

package java_systemproperty;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_SystemProperty {

    public static void main(String[] args) {
        System.out.println("user.home: " + System.getProperty("user.home"));
        System.out.println("java.home: " + System.getProperty("java.home"));
    }
    
}


Sunday, November 17, 2013

try-with-resources, introduced from Java SE 7

The try-with-resources statement is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

 static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
   return br.readLine();
  }
 }


Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

 static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
   return br.readLine();
  } finally {
   if (br != null) br.close();
  }
 }


reference: http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

Friday, November 15, 2013

Example of LinkedList vs PriorityQueue

This example demonstrate the natural ordering of PriorityQueue.

natural ordering of PriorityQueue
Natural ordering of PriorityQueue
java.util.LinkedList is a doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).

java.util.PriorityQueue is an unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException).


Example code:
package java_priorityqueue;

import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Random;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_PriorityQueue {

    public static void main(String[] args) {

        int len = 5;
        Random random = new Random();

        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(len);
        LinkedList<Integer> linkedList = new LinkedList<>();

        System.out.println("Random number generated:");
        for (int i = 0; i < len; i++) {
            Integer randomNumber = new Integer(random.nextInt(100));
            linkedList.add(new Integer(randomNumber));
            priorityQueue.add(new Integer(randomNumber));
            System.out.println(i + ": " + randomNumber);
        }
        System.out.println("Number in linkedList:");
        for (int i = 0; i < len; i++) {
            Integer item = linkedList.poll();
            System.out.println(i + ": " + item);
        }
        System.out.println("Number in priorityQueue:");
        for (int i = 0; i < len; i++) {
            Integer item = priorityQueue.poll();
            System.out.println(i + ": " + item);
        }
    }
}

Tuesday, November 12, 2013

Java Network Programming, 4th Edition

Java Network Programming, 4th Edition

This practical guide provides a complete introduction to developing network programs with Java. You’ll learn how to use Java’s network class library to quickly and easily accomplish common networking tasks such as writing multithreaded servers, encrypting communications, broadcasting to the local network, and posting data to server-side programs.
Author Elliotte Rusty Harold provides complete working programs to illustrate the methods and classes he describes. This thoroughly revised fourth edition covers REST, SPDY, asynchronous I/O, and many other recent technologies.
  • Explore protocols that underlie the Internet, such as TCP/IP and UDP/IP
  • Learn how Java’s core I/O API handles network input and output
  • Discover how the InetAddress class helps Java programs interact with DNS
  • Locate, identify, and download network resources with Java’s URI and URL classes
  • Dive deep into the HTTP protocol, including REST, HTTP headers, and cookies
  • Write servers and network clients, using Java’s low-level socket classes
  • Manage many connections at the same time with the nonblocking I/O
October 14, 2013  1449357679  978-1449357672 Fourth Edition


Sunday, November 10, 2013

Get screen size using javafx.stage.Screen

javafx.stage.Screen class describes the characteristics of a graphics destination such as monitor. In a virtual device multi-screen environment in which the desktop area could span multiple physical screen devices, the bounds of the Screen objects are relative to the Screen.primary. We can obtain the width and height of screen by calling Screen.getPrimary().getVisualBounds().getWidth() and Screen.getPrimary().getVisualBounds().getHeight().

This example set the application run in full screen.
application run in full screen
JavaFX application run in full screen

package javafx_screen;

import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Screen;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Screen extends Application {

    @Override
    public void start(Stage primaryStage) {
        
        Rectangle2D visualBounds = Screen.getPrimary().getVisualBounds();
        
        Label label = new Label();
        label.setText(
                visualBounds.getWidth() + " x " + visualBounds.getHeight());

        StackPane root = new StackPane();
        root.getChildren().add(label);
        
        Scene scene = new Scene(root, 
                visualBounds.getWidth(), visualBounds.getHeight());
        
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Saturday, November 9, 2013

JavaFX example: how to set icon of application window

This example show how to set icon of application window, by calling:

Stage.getIcons().add(applicationIcon);

Also show how to set icon dynamically at run-time, when 'Hello World' button clicked.

set icon of application window
set icon of application window

package javafx_applicationicon;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_ApplicationIcon extends Application {

    @Override
    public void start(final Stage primaryStage) {

        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
                
                //load another image from internet
                //and dynamically add it as new apllication icon
                Image anotherIcon = new Image("http://goo.gl/kYEQl");
                primaryStage.getIcons().add(anotherIcon);
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        
        Scene scene = new Scene(root, 300, 250);
        
        //set icon of the application
        Image applicationIcon = new Image(getClass().getResourceAsStream("dukes_36x36.png"));
        primaryStage.getIcons().add(applicationIcon);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
}

Sunday, November 3, 2013

Store numbers of different types in a List

To store numbers of different types (Integer, Float, Double...) in a single List, we can define the list of type Number.

Example:

package javanumber;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaNumber {

    public static void main(String[] args) {
        List<Number> numberList = new ArrayList<>();
        numberList.add((int)123);
        numberList.add(123456.7);
        numberList.add((double)456.789);
        numberList.add(0.1f);
        
        for(Number num:numberList){
            System.out.println(num + " of type " + num.getClass());
        }
    }
}

List contain numbers of different type
A single List contain numbers of Integer, Double and Integer