Saturday, October 31, 2015

Let's make Life game 1

Do you know "life," the game? Life game isn't Jinsei game. Life game is a simulation game made by a mathematician.
The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.
The "game" is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves or, for advanced players, by creating patterns with particular properties.
-Wikipedia Conway's game of life
We will make this gama with java as a practice.

Download things we need for the Swing 

We will make the game with Swing. To use Swing, we need to prepare some things. At first, run your Eclipse.

Click "Help" and then "Install New Software"


2, Inside the box named "Work with:", copy this URL:http://download.eclipse.org/releases/mars/ and paste it to the box (If you are using Kepler, then write "http://download.eclipse.org/releases/kepler/". The URL which you need changes depending on the version of Eclipse). Then you will see the display will be changed like this:

In the below box, find "General Purpose Tools".


Inside the General Purpose Tools, find Swing Designer and Swing Designer Documentation and check both of them. 
Then click next.

You will see this display:

Just click "next" again.

Now you will see this:


Please check "I accept the terms of the license agreement" after reading it and click "Finish".

After finishing the download, you need to restart the Eclipse. When you finish restarting, now you can use SwingDesigner.



Multi threading (detailed)

What is Thread?
Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class.
--cited from Java Threads Tutorial | Wideskills


This is the thread. Well, we can consider the thread as a robot which executes tasks within a program. We usually have only one main robot which executes tasks within a program (this robot is called "main thread"). But what if there is a tough task which takes a lot of time to execute...During the main robot executes the task, no robot can execute other tasks within a program. As a result, the program freezes during the main thread executes the tough task.

main robot is working.
image cited from: http://java2005.cis.k.hosei.ac.jp/materials/lecture26/multithreaded.html

Another robot was added.
image cited from: http://java2005.cis.k.hosei.ac.jp/materials/lecture26/multithreaded.html

How to use the multi threading

There are two ways to use the multi threading. One is to extends Thread class as following:

Extend Thread class

class Test {
    public static void main(String[] args) {
        SubTest tt = new SubTest();
        tt.start();
    }
}

class SubTest extends Thread {
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println( i + " Hello World");
        }
    }
}

SubTest class is extending Thread class. Then an object of SubTest class is created inside the main method of Test class. 

Once we execute the start method of Thread class, codes in-between the "run(){" and "}" are executed as follows:
result.

Implements Runnable interface

The another way is to implement runnable interface. See below for the code.

class Test {
    public static void main(String[] args) {
        SubTest tt = new SubTest();
        Thread t = new Thread(tt);
        t.start();
    }
}

class SubTest implements Runnable {
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i + " Hello World");
        }
    }
}

Result.

It is forbidden to extend multiple classes at once. Thus, if we want to use multi-threading though we are already extending one class, we must use this second way.

Synchronized

Please see the below program. This creates 10 threads and displays how many times the method was executed in this program.

---------------------------------
class Test {
    static Counter counter = new Counter();

    public static void main(String[] args) {

        // Create 10 threads
        MyThread[] threads = new MyThread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new MyThread();
            threads[i].start();
        }

        // wait until all threads finish
        for (int i = 0; i < 10; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }

        // display the counter
        System.out.println(Test.counter.count);
    }
}

// thread
class MyThread extends Thread {
    public void run() {
        Test.counter.countUp(); //this indicates the countUp method below
    }
}

// counter
class Counter {
    int count;
    void countUp() {
        System.out.print("Hello, ");
        int n = count;            // the number n becomes the variable "count"
        System.out.print("World");
        count = n + 1;            // 1 is added to n. 
        //Every time this method is executed, the count's number increases by 1.
        System.out.println("!!");
    }
}
---------------------------------

Result 1: It displays 10.

Result 2: Sometimes it doesn't display 10. 

The result is shown above. But sometimes this doesn't display 10 which is the correct number. See Result 2 for the wrong result. In the Result 2, it displays 5. Why does this occur?

The Counter class has the reason why this is happening. We had 10 threads and some of the threads simultaneously executed the countUp method of Counter class, that is why, while one thread was executing countUp method, another thread simultaneously executed the countUp method. This resulted in the wrong result like Result 2 above.

This displays "Hello, WorldHello, World!!" which is missing another "!!" at the end.
Another "!!" shows up after 4 threads displays the "Hello, World!!", which means 1+4 threads cut in while one thread was exexcuting.

To avoid this "cutting-in-threads" problem, use "synchronized" statement as follows:
--------------------------------
void countUp() {
        synchronized (this) {
            System.out.print("Hello, ");
            int n = count;             // the number n becomes the variable "count"
            System.out.print("World");
            count = n + 1;            // 1 is added to n. 
            //Every time this method is executed, the count's number increases by 1.
            System.out.print("!!");
        }
    }
---------------------------------

The whole picture would be:

---------------------------------
class Test {
    static Counter counter = new Counter();

    public static void main(String[] args) {

        // Create 10 threads
        MyThread[] threads = new MyThread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new MyThread();
            threads[i].start();
        }

        // wait until all threads finish
        for (int i = 0; i < 10; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }

        // display the counter
        System.out.println(Test.counter.count);
    }
}

// thread
class MyThread extends Thread {
    public void run() {
        Test.counter.countUp(); //this indicates the countUp method below
    }
}

// counter
class Counter {
    int count;
    void countUp() {
        synchronized (this) {
            System.out.print("Hello, ");
            int n = count;             // the number n becomes the variable "count"
            System.out.print("World");
            count = n + 1;            // 1 is added to n. 
            //Every time this method is executed, the count's number increases by 1.
            System.out.println("!!");
        }
    }
}
---------------------------------

Synchronized statement forbids the threads to execute the method simultaneously. That is why the threads don't get confused and are always displaying the correct result.

By the way, Synchronized statement can be written as follows also:
---------------------------------
class Global {
    static Object lock = new Object();
}

class Counter {
    void countUp() {
        synchronized (Global.lock) {
            // write your code here
        }
    }
}
---------------------------------

How to add scroll bar

How to use the scroll pane.

at first the scroll bar is invisible but when the text inside becomes long enough, it appears.

-------------------------------------------------------------------------
import javax.swing.*;
import java.awt.BorderLayout;

public class Main extends JFrame{

 Main(){
     JTextArea textarea = new JTextArea("This is JTextArea");

     JScrollPane scrollpane = new JScrollPane(); //Scroll bar
     scrollpane.setViewportView(textarea);

     getContentPane().add(scrollpane, BorderLayout.CENTER);
  }

 public static void main(String[] args) {
     Main frame = new Main();

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setBounds(10, 10, 300, 200);
     frame.setTitle("Title");
     frame.setVisible(true);
 }
}

------------------------------------------------------------------------------

Tuesday, October 27, 2015

fetch a current directory

This program fetch a current directory.

code:

public class Test1 { public static void main(String[] args) { System.out.println(getCurrentDir()); } public static String getCurrentDir(){ String path = new File(".").getAbsoluteFile().getParent(); return path; }
}

Saturday, October 24, 2015

Adding buttons automatically VS Using Button-like-cells

To add ActiveX controls automatically on the sheet by VBA, write codes as follows:

Sub Add_OLEObject_Test()
   Dim objOLE As OLEObject
   Dim i      As Long
        Set objOLE = Worksheets("Sheet1").OLEObjects.Add("Forms.CommandButton.1")
        objOLE.Name = "CommandButton1"   'Name of the control
        objOLE.Left = 10           'Location of the control
        objOLE.Top = 10            'Location of the control
End Sub


We can add a new ActiveX button's code on the VBE by writing this way:

Sub WriteTest()
    n = Worksheets("Sheet1").OLEObjects.Count
    With ThisWorkbook.VBProject.VBComponents("Module1").CodeModule
        .InsertLines 1, vbTab & "Sub CommandButton" & n & "_Click"
        .InsertLines 2, vbTab & "msgbox ""under construction"""
        .InsertLines 3, vbTab & "End sub"
    End With
End Sub

n represents how many ActiveX controls are existing on the sheet.

n = Worksheets("Sheet1").OLEObjects.Count

That is to say, n counts how many ActiveX controls are exisiting; if there are 2 controls on the sheet, n becomes 2. Thus, by using the number and "InsertLines", we can automatically add codes in VBE for new controls we have added. But what if there is a small glitch and codes for the second button are inserted in line 2?  That would look like this:

Sub CommandButton1_Click()
Sub CommandButton2_Click()
End Sub
End Sub 

This never works properly and we can see how small glitch destroys the whole system. So I don't recommend writing codes this way to dynamically add new buttons on sheets.

Much better way would be using cells as if they are buttons. To use such button-like-cells, write codes this way (then copy and paste it to the sheet's code-editor for which you want to use the button-like-cells):

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    a = Target.Row
    b = Target.Column
        If a >= 1 And a <= 5 And b = 1 Then
            MsgBox "Hello"
        ElseIf  a >= 1 And a <= 5 And b = 2 Then
            MsgBox "Good morning"
        End If
End Sub

This code enables you to use the button-like-cells. You can administrate many buttons at a same time this way. If you click one of cells from A1 to A5, a message box saying "Hello" appears. If you click one of cells from B1 to B5, a message box saying "Good morning" appears.

That is, all cells between A1 and A5 and all cells between B1 to B5 became buttons which show a message box when it is clicked. It is MUCH BETTER to button-like-cells to deal with many almost-same buttons than automatically adding many new ActiveX buttons and its codes by "Insert codes" things.

In addition, I will give you one more code that can be useful when dealing with many button-like-cells for a table.

lastRow = Worksheets("Sheet1").Range("A1").End(xlDown).Row

This variable "lastRow" shows the Row-number of the lowest one of cells that are existing under A1. Please note all cells must have the value to be counted by this code: empty cell is always considered as the end of row. (except if all cells are empty)

Using this code, we can fetch the lowest row of a table, that can be useful to deal with many button-like-cells for a table. For example:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    a = Target.Row
    b = Target.Column
    lastRow = Worksheets("Sheet1").Range("A1").End(xlDown).Row
    If a >= 1 And a <= lastRow And b = 1 Then
        MsgBox "Hello"
    ElseIf  a >= 1 And a <= lastRow And b = 2 Then
        MsgBox "Good morning"
    End If
End Sub

We can administrate all button-like-cells between A1 and the lowest row of a table at a same time. Or all button-like-cells between B1 and the lowest row of a table at a same time.

Saturday, October 17, 2015

Multi Thread programming

There are two ways for multi thread programming: one is extending Thread class, and the other is implementing Runnable interface. I will show you the second way here; implementing Runnable interface. I used this way in this post.

To do the multi thread programming, you must do the following things:

1, Create a class which implements Runnable interface.
2, Implement run methond inside the class.
3, Create an object of the class.
4, Create an object of Thread class with a constructor of which the argument is the object (which we have created in 3.)
5, Use the start method of the object of the Thread class.

public class Test1 implements Runnable { public void run() { for (int i = 0; i <= 10 ; i++) { System.out.println(i + "Hello, world!"); } } public static void main(String[] args) { Test1 test1 = new Test1(); Test1 test2 = new Test1(); Thread t1 = new Thread(test1); Thread t2 = new Thread(test2); t1.start(); t2.start(); } }

Result. You can see there are two threads.

Further reading
What is a thread? - Web based programming tutorials
http://www.webbasedprogramming.com/Java-Unleashed-Second-Edition/ch9.htm

Friday, October 16, 2015

USA unemployment data year by year

I made an macro with VBA in an excel, where you can search unemployment rate of USA. The data was taken from IMF database. Please note, that's why, this excel contains "macro",

Download from:
https://www.dropbox.com/s/7krsqzbl4ht1cn6/USAemployement.xlsm?dl=0

code:
please see inside the Excel.

Thursday, October 15, 2015

How to connect to MS access from Excel

The code below is a sample code which connects to MS access from Excel. Please note that you need to enable ActiveX Data Objecys X.X library in the reference to use this code.

Sample Excel file:
https://www.dropbox.com/s/tszrdiy3jzvjq5r/Sample.zip?dl=0

Code:
Private Sub Test()
    Dim adoCON      As New ADODB.Connection
    Dim adoRS       As New ADODB.Recordset
    Dim strSQL      As String
    Dim odbdDB      As Variant
    Dim wSheetName  As Variant
    Dim i           As Integer
    Dim Num1        As Integer
   
    odbdDB = ActiveWorkbook.Path & "\DB_name.accdb"

    adoCON.ConnectionString = "provider=Microsoft.ACE.OLEDB.12.0;" _
                        & "Data Source=" & odbdDB & ""
    adoCON.Open
    adoCON.BeginTrans

    adoRS.CursorLocation = adUseClient

    'SQL for the database
        strSQL = "SELECT * FROM  table_name ORDER BY table_name.ID;"
    'If you want to search a certain thing, write as follows:
    'strSQL = "SELECT table_name.* FROM table_name WHERE subject_of_the_table = " & TextBox1.Value & ";"
    'If this is string data type, you must write as: strSQL = "SELECT * FROM table_name WHERE subject_of_the_table  LIKE '" & TextBox1.Value & "';"


    adoRS.Open strSQL, adoCON, adOpenDynamic
 
    i = 1

    Do Until adoRS.EOF
        With Worksheets("Sheet1")
            .Cells(i, 1).Value = adoRS!ID
            .Cells(i, 2).Value = adoRS!Name
            .Cells(i, 3).Value = adoRS!age
        End With
        i = i + 1
        adoRS.MoveNext
    Loop
    adoCON.CommitTrans

    adoRS.Close
    Set adoRS = Nothing
    adoCON.Close
    Set adoCON = Nothing
   
End Sub

Highlighted words with blue are depending on your MSaccess file. So you must change the blue-highlighted-words depending on your MSaccess file.

Although you copied and pasted this code to your VBA editor's window, you can't access to the database? If so, maybe you have not changed the setting of  references.

If you see the following error message:
User-defined type not defined
Then it is probably because of the references settings.

Go to the VBA editor.


Then select Tools from the menu. Then select "References".

If you can not click the references button, maybe some macro is working. Click the stop button as follows;

Then you see the below window. Look for Microsoft ActiveX Data Objects X.X Library. The version of ADO can be different, so select the latest one.


Click "OK" in the upper right of the window. Now you can use the ADO in your Excel.


Euro Area Population & Unemployment data.

Population & Unemployment & Employment data taken from IMF's data base. I made it in Excel file. I made a macro so that you can search the data in the Excel. Please note, that's why, this excel contains "macro",

Download:
https://www.dropbox.com/s/vblxjljma7m9jnc/EuroAreaData.xlsm?dl=0

Code:
Please see inside of the Excel.

Tuesday, October 13, 2015

PC info checker

This program scans your local IP address and Subnet mask then displays it.

Download the runnable jar file from:
https://www.dropbox.com/s/vohjz2tca5hbejd/PCInfoScanner.jar?dl=0


Port scanner (doesn't freeze during its process)

Now I've made a port scanner which doesn't freeze during its process. I've used the multi-thread programming for this. Please check the code for the detail.

Download the runnable jar file:
https://www.dropbox.com/s/t84sp78rlbev9od/PortScanner.jar?dl=0

Code:

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class PortScanner extends JFrame {
 JTextArea textarea;


 private JPanel contentPane;
 private JTextField textField;
 private JTextField textField_1;
 private JLabel lblPortScanner;
 private final Action action = new SwingAction();
 private JLabel lblNewLabel_2;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {

  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     PortScanner frame = new PortScanner();
     frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });

 }

 /**
  * Create the frame.
  */
 public PortScanner() {
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 450, 500);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  contentPane.setLayout(null);

  textField = new JTextField();
  textField.setBounds(133, 71, 167, 19);
  contentPane.add(textField);
  textField.setColumns(10);

  JLabel lblNewLabel = new JLabel("From");
  lblNewLabel.setBounds(171, 48, 80, 13);
  contentPane.add(lblNewLabel);

  textField_1 = new JTextField();
  textField_1.setBounds(133, 123, 167, 19);
  contentPane.add(textField_1);
  textField_1.setColumns(10);

  JLabel lblNewLabel_1 = new JLabel("To");
  lblNewLabel_1.setBounds(171, 100, 68, 13);
  contentPane.add(lblNewLabel_1);

  lblPortScanner = new JLabel("Port Scanner");
  lblPortScanner.setBounds(170, 25, 87, 13);
  contentPane.add(lblPortScanner);

  textarea = new JTextArea();
  textarea.setBounds(43, 195, 355, 240);
  contentPane.add(textarea);

  JButton btnGo = new JButton("Go");
  btnGo.setAction(action);
  btnGo.setBounds(177, 163, 80, 21);
  contentPane.add(btnGo);

  lblNewLabel_2 = new JLabel("");
  lblNewLabel_2.setBounds(159, 141, 115, 13);
  contentPane.add(lblNewLabel_2);
 }

 private class SwingAction extends AbstractAction implements  Runnable{

  public SwingAction() {
   putValue(NAME, "Go");
   putValue(SHORT_DESCRIPTION, "Some short description");
  }

  public void run() {
   textarea.setText("");
   String textFieldValue = textField.getText();
   String textFiledValue1 = textField_1.getText();
   String host = "localhost";
   lblNewLabel_2.setText("Scanning...");

      try {
        InetAddress theAddress = InetAddress.getByName(host);

        for (int i = Integer.parseInt(textFieldValue); i < Integer.parseInt(textFiledValue1); i++) {
        try {
          Socket theSocket = new Socket(theAddress, i);
             textarea.append("There is a server on port " + i + " of " + host + "\n");

             }
             catch (IOException ex) {
              System.err.println(ex);
             }
   
         }
   
         }
      catch(UnknownHostException ex) {
       System.err.println(ex);
      }
  lblNewLabel_2.setText("Scan finished");
  }

  public void actionPerformed(ActionEvent e) {
   SwingAction sa1 = new SwingAction();
   Thread t1 = new Thread(sa1);
   t1.start();
  }
 }
}

Monday, October 12, 2015

Port Scanner (GUI)

I've made a port scanner but it seems to freeze until the whole scanning is finished. Maybe I need the multi-thread programming for solving this problem...but multi-thread seems hard for me.

code:

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class PortScanner extends JFrame {
 JTextArea textarea;


 private JPanel contentPane;
 private JTextField textField;
 private JTextField textField_1;
 private JLabel lblPortScanner;
 private final Action action = new SwingAction();
 private JLabel lblNewLabel_2;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
 
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     PortScanner frame = new PortScanner();
     frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 
 }

 /**
  * Create the frame.
  */
 public PortScanner() {
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 450, 500);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  contentPane.setLayout(null);
 
  textField = new JTextField();
  textField.setBounds(133, 71, 167, 19);
  contentPane.add(textField);
  textField.setColumns(10);
 
  JLabel lblNewLabel = new JLabel("From");
  lblNewLabel.setBounds(171, 48, 80, 13);
  contentPane.add(lblNewLabel);
 
  textField_1 = new JTextField();
  textField_1.setBounds(133, 123, 167, 19);
  contentPane.add(textField_1);
  textField_1.setColumns(10);
 
  JLabel lblNewLabel_1 = new JLabel("To");
  lblNewLabel_1.setBounds(171, 100, 68, 13);
  contentPane.add(lblNewLabel_1);
 
  lblPortScanner = new JLabel("Port Scanner");
  lblPortScanner.setBounds(170, 25, 87, 13);
  contentPane.add(lblPortScanner);
 
  textarea = new JTextArea();
  textarea.setBounds(43, 195, 355, 240);
  contentPane.add(textarea);
 
  JButton btnGo = new JButton("Go");
  btnGo.setAction(action);
  btnGo.setBounds(177, 163, 80, 21);
  contentPane.add(btnGo);
 
  lblNewLabel_2 = new JLabel("");
  lblNewLabel_2.setBounds(159, 141, 115, 13);
  contentPane.add(lblNewLabel_2);
 }
 private class SwingAction extends AbstractAction {
 
  public SwingAction() {
   putValue(NAME, "Go");
   putValue(SHORT_DESCRIPTION, "Some short description");
  }
  public void actionPerformed(ActionEvent e) {
   String textFieldValue = textField.getText();
   String textFiledValue1 = textField_1.getText();
   String host = "localhost";
   lblNewLabel_2.setText("Scanning...");

     try {
       InetAddress theAddress = InetAddress.getByName(host);
       for (int i = Integer.parseInt(textFieldValue); i < Integer.parseInt(textFiledValue1); i++) {
       try {
         Socket theSocket = new Socket(theAddress, i);
            textarea.append("There is a server on port " + i + " of " + host + "\n");
                 
            }
            catch (IOException ex) {
               }
       }
     }
     catch(UnknownHostException ex) {
      System.err.println(ex);
     }
  }
 }
}

Prime number checker

This is a runnable jar file. This check if a number is a prime number or not.

Download from:
https://www.dropbox.com/s/943fciwxvo0zapa/Primenumcheck.jar?dl=0

Code:

import java.awt.EventQueue;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;


public class GUItest extends JFrame {

 private JPanel contentPane;
 private JTextField textField;
 private final Action action = new SwingAction();
 private JLabel lblEnterANumber;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     GUItest frame = new GUItest();
     frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the frame.
  */
 public GUItest() {
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 450, 300);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  contentPane.setLayout(null);
 
  JLabel lblNewLabel = new JLabel("Prime number checker");
  lblNewLabel.setBounds(128, 32, 157, 13);
  contentPane.add(lblNewLabel);
  lblNewLabel.setHorizontalAlignment(lblNewLabel.CENTER);
 
  textField = new JTextField();
  textField.setBounds(147, 101, 116, 24);
  contentPane.add(textField);
  textField.setColumns(10);
 
  JButton btnNewButton = new JButton("Check");
  btnNewButton.setAction(action);
  btnNewButton.setBounds(147, 182, 116, 21);
  contentPane.add(btnNewButton);
 
  lblEnterANumber = new JLabel("Enter a number");
  lblEnterANumber.setBounds(68, 135, 283, 13);
  contentPane.add(lblEnterANumber);
     lblEnterANumber.setHorizontalAlignment(lblEnterANumber.CENTER);
 }
 private class SwingAction extends AbstractAction {
  public SwingAction() {
   putValue(NAME, "Check");
   putValue(SHORT_DESCRIPTION, "Starts the calculation");
  }
  public void actionPerformed(ActionEvent e) {
   String textFieldValue = textField.getText() + "l";
   long num1 = Long.valueOf(textFieldValue).longValue();
   
   if(isNumber(textFieldValue) ){
    display(num1);
   }else{
    lblEnterANumber.setText("This is a too big number or String data.");
   }
   
  }

     private void display(long Num){
      if( isPrimeNum( Num ) ) {
       lblEnterANumber.setText( Num + " is a prime number." );
      } else{
       lblEnterANumber.setText( Num +" isn't a prime number.");
      }
     }

  private boolean isPrimeNum( long x ) {
      if( x == 2 )
      return true;

      if( x < 2 || x % 2 == 0 )
      return false;

      for( long a = 3; a <= Math.sqrt((double)x); a += 2 )
      if( x % a == 0 )
      return false;
 
      return true;
  }
 
  public boolean isNumber(String val) {
   try {
    Integer.parseInt(val);
    return true;
   } catch (NumberFormatException nfex) {
    return false;
      }
  }
 }
}

File Info checker

This is .exe file called "File Info". You can check the detail of the file which you choose in your PC.

Download from
https://www.dropbox.com/s/fyww28guqop9d9d/FileInfo.exe?dl=0
Copy right of the original photo
Author: Matthew McClintock
Licence : Design Science License
Commercial use : Yes
Link: http://icones.pro/en/beos-book-help-png-image.html

Code:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Locale;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class MimeGUI extends JFrame implements ActionListener{

  JTextArea textarea;

  public static void main(String[] args){

 
    MimeGUI frame = new MimeGUI();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(10, 10, 500, 300);
    frame.setTitle("File Info Scanner");
    frame.setVisible(true);
 

  }

  MimeGUI(){
    JButton button = new JButton("file select");
    button.addActionListener(this);

    JPanel buttonPanel = new JPanel();
    buttonPanel.add(button);

    textarea = new JTextArea();
    textarea.setLineWrap(true);

    JScrollPane scrollpane = new JScrollPane(textarea);
    scrollpane.setBounds(40, 10, 400, 200);
    scrollpane.setPreferredSize(new Dimension(400, 300));

    JPanel textPanel = new JPanel();
    textPanel.setLayout(null);
    textPanel.add(scrollpane);

    getContentPane().add(textPanel, BorderLayout.CENTER);
    getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
 
  }

  public void actionPerformed(ActionEvent e){

    JFileChooser filechooser = new JFileChooser();

    int selected = filechooser.showOpenDialog(this);
    if (selected == JFileChooser.APPROVE_OPTION){
      File file = filechooser.getSelectedFile();

      textarea.setText("");

      try{
        if (checkBeforeReadfile(file)){
          BufferedReader br = new BufferedReader(new FileReader(file));

          Path source = Paths.get(file.getPath());
    String mime = Files.probeContentType(source);

          textarea.append("Location : " + file.getPath() + "\n\n\n");
          textarea.append("File name : " + file.getName() + "\n");
          textarea.append("File size: " + String.valueOf(getKB(file.length())) + "KB\n");
          textarea.append("Extension: " + getSuffix(file.getName()) + "\n");
          textarea.append("File mime type: " + mime + "\n");

          SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.US);
          textarea.append("Last modified time: " + sdf.format(file.lastModified()) + " (US time)");

          br.close();
        }else{
          System.out.println("Can't find or open the file");
        }
      }catch(FileNotFoundException err){
        System.out.println(err);
      }catch(IOException err){
        System.out.println(err);
      }
    }
  }

  private static boolean checkBeforeReadfile(File file){
    if (file.exists()){
      if (file.isFile() && file.canRead()){
        return true;
      }
    }

    return false;
  }

 private static BigDecimal getKB(long byte1){
  double kbyte1;
  double byte2;

  byte2 = byte1;
  kbyte1 = byte2/1024;

  BigDecimal value = new BigDecimal(kbyte1);
  BigDecimal roundHalfUp1 = value.setScale(2, BigDecimal.ROUND_HALF_UP);

  return roundHalfUp1;
 }

 private static String getSuffix(String FileName) {
     if (FileName == null)
           return null;
        int point = FileName.lastIndexOf(".");
        if (point != -1) {
            return FileName.substring(point + 1);
        }
        return FileName;
    }
}

Check Mime type

You designate a path of a file to detect Mime type.
When you designate the file path, write this way:
C:\\Users\\John\\Pictures\\blog\\1alignment_panel.gif


import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class TestMime { public static void main(String[] args) throws IOException { BufferedReader buffreader1 = new BufferedReader(new InputStreamReader(System.in)); String mpath = ""; mpath = buffreader1.readLine(); File file = new File(mpath); Path source = Paths.get(file.getPath()); System.out.println(Files.probeContentType(source)); } }

Mime type detector

This program detects the Mime type. Designate the file by writing a path of the file.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class TestMime {
   public static void main(String[] args) throws IOException {
     Path source = Paths.get("c:/temp/0multipage.tif"); // Write a path of the file here.
     System.out.println(Files.probeContentType(source));
     // output : image/tiff
   }
}

Saturday, October 10, 2015

How to make a runnable JAR file.

1, Open the Eclipse.


2, Choose the project you want to export as an executable file. And right click on it.

3, Choose "Export".
4, Choose the "Runnable JAR file". Then "Next".
5, Choose "Finish". But if your program has any error, you can not choose the Finnish button.

Prime number check (GUI programming using Swing)

You need "Swing" to run this program.

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;


public class GUItest extends JFrame {

 private JPanel contentPane;
 private JTextField textField;
 private final Action action = new SwingAction();
 private JLabel lblEnterANumber;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     GUItest frame = new GUItest();
     frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the frame.
  */
 public GUItest() {
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 450, 300);
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  contentPane.setLayout(null);
 
  JLabel lblNewLabel = new JLabel("Prime number checker");
  lblNewLabel.setBounds(128, 32, 157, 13);
  contentPane.add(lblNewLabel);
  lblNewLabel.setHorizontalAlignment(lblNewLabel.CENTER);
 
  textField = new JTextField();
  textField.setBounds(147, 101, 116, 24);
  contentPane.add(textField);
  textField.setColumns(10);
 
  JButton btnNewButton = new JButton("Check");
  btnNewButton.setAction(action);
  btnNewButton.setBounds(147, 182, 116, 21);
  contentPane.add(btnNewButton);
 
  lblEnterANumber = new JLabel("Enter a number");
  lblEnterANumber.setBounds(68, 135, 283, 13);
  contentPane.add(lblEnterANumber);
     lblEnterANumber.setHorizontalAlignment(lblEnterANumber.CENTER);
 }
 private class SwingAction extends AbstractAction {
  public SwingAction() {
   putValue(NAME, "Check");
   putValue(SHORT_DESCRIPTION, "Starts the calculation");
  }
  public void actionPerformed(ActionEvent e) {
   String textFieldValue = textField.getText();
   long num1 = Long.valueOf(textFieldValue).longValue();
   
   if(isNumber(textFieldValue) ){
    display(num1);
   }else{
    lblEnterANumber.setText("This is a too big number or String data.");
   }
   
  }

     private void display(long Num){
      if( isPrimeNum( Num ) ) {
       lblEnterANumber.setText( Num + " is a prime number." );
      } else{
       lblEnterANumber.setText( Num +" isn't a prime number.");
      }
     }

  private boolean isPrimeNum( long x ) {
      if( x == 2 )
      return true;

      if( x < 2 || x % 2 == 0 )
      return false;

      for( long a = 3; a <= Math.sqrt((double)x); a += 2 )
      if( x % a == 0 )
      return false;
 
      return true;
  }
 
  public boolean isNumber(String val) {
   try {
    Integer.parseInt(val);
    return true;
   } catch (NumberFormatException nfex) {
    return false;
      }
  }
 }
}

Wednesday, October 7, 2015

Low port scanner

This scans available ports. Please note that there are some dangerous ports among them.

import java.net.*;
import java.io.*;

public class LowPortScanner {

 public static void main(String args[]) {

  String host = "localhost";
 
  if(args.length > 0) {
   host = args[0];
  }

  try {
   InetAddress theAddress = InetAddress.getByName(host);
   for (int i = 1; i < 1024; i++) {
   try {
    Socket theSocket = new Socket(theAddress, i);
    System.out.println("There is a server on port " + i + " of " + host);
   }
   catch (IOException ex) {
   
   }
  }
 }
 catch(UnknownHostException ex) {
  System.err.println(ex);
 }
 }
}

High port Scanner

This program scans available ports. Note that there are some dangerous ports.

import java.net.*;
import java.io.*;

public class HighPortScanner {

 public static void main(String args[]) {

  String host = "localhost";

  if(args.length > 0) {
   host = args[0];
  }

  try {
   InetAddress theAddress = InetAddress.getByName(host);
   for (int i = 49152; i < 65536; i++) {
   try {
    Socket theSocket = new Socket(theAddress, i);
    System.out.println("There is a server on port " + i + " of " + host);
   }
   catch (IOException ex) {
 
   }
  }
 }
 catch(UnknownHostException ex) {
  System.err.println(ex);
 }
 }
}

Get kilo byte

This is a method which transforms a long data of byte to Kilo byte. You need to import BigDecimal to use this method.

import java.math.BigDecimal; private static BigDecimal getKB(long byte1){ double kbyte1; double byte2; byte2 = byte1; kbyte1 = byte2/1024; BigDecimal value = new BigDecimal(kbyte1); BigDecimal roundHalfUp1 = value.setScale(2, BigDecimal.ROUND_HALF_UP); return roundHalfUp1; }

IP address (local IP address) finder

This progran scans your IP address and the hostname then displays both of them. This program throws an exception "unknown host exception."

import java.net.InetAddress; import java.net.UnknownHostException; public class IpAddressFinder { public static void main(String[] args) { // Get the local host name and the IP address. try { InetAddress addr = InetAddress.getLocalHost(); System.out.println("Local Host Name: " + addr.getHostName()); System.out.println("IP Address : " + addr.getHostAddress()); } catch (UnknownHostException e) { e.printStackTrace(); } } }

Tuesday, October 6, 2015

How to import JavaDoc of external libraries to your Eclipse

If you import external libraries to your Eclipse, now you need to import JavaDoc for the description of Methods and Class of  the external libraries. If you have the JavaDoc in your Eclipse, if you place the cursor on a method of the external library, you can read an explanation of the method.

To import it, you need to download JavaDoc for the library from somewhere. Once downloading it, you open your Eclipse. Open your project explorer and right-click on a name of project to which you want to import the JavaDoc.

Then choose "JavaDoc Location" then "Browse".


And choose the file of the JavaDoc.

InetAddress Class

Generally speaking, "InetAddress" class provides methods to resolve host names to their IP addresses and vice versa.
This program shows how to use the InetAddress class. This program gets the IP address and the domain.


import java.io.*;
import java.net.*;
public class InetAddressDemo {
   public static void main(String args[]) {
      try {
         String host = "noteoneverything.blogspot.com";
         InetAddress ip = InetAddress.getByName(host);
         System.out.println("IP Address : " + ip.getHostAddress());
         System.out.println("Hostname : " + ip.getHostName());
      } catch(UnknownHostException uhe) {
         System.out.println("Host Not Found");
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}

Chat program (Client program)

This is a chat program which I found here.

import java.io.*;
import java.net.*;
public class MyChatClient {
   public static void main(String args[]) {
      try {
         Socket skt = new Socket("127.0.0.1", 8999);
         System.out.println("Connected to server");

         InputStream is = skt.getInputStream();
         ObjectInputStream ois = new ObjectInputStream(is);
         OutputStream os = skt.getOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(os);

         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

         String rcv_msg, send_msg;
         while(true) {
            // Send a message to Server
            System.out.print("To Server : ");
            send_msg = br.readLine();
            oos.writeObject(send_msg);

            // Recieve a message from Server */
            System.out.println("Waiting for server to respond ... ");
            if((rcv_msg = (String)ois.readObject()) != null) {
               System.out.println("\nFrom Server : " + rcv_msg);
            }
         }
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}

Chat program (Server program)

A chat program (server) which I found here.

------------------------------------------
import java.io.*; import java.net.*; public class MyChatServer { public static void main(String args[]) { try { // Create a new server socket that listens at a port ServerSocket ss = new ServerSocket(Write your port number here); System.out.println("Server is lisenting ... "); Socket skt = ss.accept();//accept a connection from client on the port OutputStream os = skt.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); InputStream is = skt.getInputStream(); ObjectInputStream ois = new ObjectInputStream(is); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String rcv_msg, send_msg; while(true) { // Recieve a message from client System.out.println("Waiting for client to respond ... "); if((rcv_msg = (String)ois.readObject()) != null) { //(String)ois.readObject() is substituted to rcv_msg,
//which means rcv_msg is the received message from the client System.out.println("From Client : " + rcv_msg); } // Send a message to client System.out.print("\nTo Client : "); send_msg = br.readLine(); //Accepting command line argument oos.writeObject(send_msg); //Sending the message which is named as "send_msg" } } catch(Exception e) { System.out.println(e); } } }
------------------------------------------
References
csegeeks.com "Network Programming with Java" Java tutorial, retrieved on 23rd November 2015

Monday, October 5, 2015

VBA autofilter

In VBA, autofilter is useful to search specific information you want from a data range.


Worksheets("Sheet1").Range("A4:D30").AutoFilter field:=1, Criteria1:="JASON"

This is the autofilter. In the range from A4 cell to D30 cell, this arranges the data. But you can decide how it arranges the data.

The property Field 1 means the field of searching. If you write 1 for the Field property, then this searches the left-most line. If you write 2 for the Field property, this searches the second leftmost line. Criteria1 is the condition of search. This shows all data of JASON of the search range.

If you want to copy and paste the result of the filtering, write codes as follows:
lastRow = Worksheets("Sheet1").Range("A4").End(xlDown).Row
Worksheets("Sheet1").Range("A5:D" & lastRow).Copy
Worksheets("Sheet4").Range("A7").PasteSpecial
If you want to finish the filtering, write the autofilter method again. You don't need to write the properties for the method again.
Worksheets("Sheet1").Range("A4:D30").AutoFilter
Then the filtering stops working.

You can check if the sheet is in filter mode as following:

    If Worksheets("Sheet1").FilterMode = True Then
        Worksheets("Sheet1").Range("A4:D30").AutoFilter
    End If

If the sheet is in filter mode, this switches it off.

The code below is a sample code. If the value of combo-box is "option1", this searches for "1000" in range of A4:D30 in worksheet1. Then the result is copied to worksheet4.

Private Sub ComboBox1_Change()
If ComboBox1.Value = "Option1" Then
Worksheets("Sheet4").Range("A7:D30").Clear

    If Worksheets("Sheet1").FilterMode = True Then
        Worksheets("Sheet1").Range("A4:D30").AutoFilter
    End If

Worksheets("Sheet1").Range("A4:D30").AutoFilter Field:=1, Criteria1:="1000"
lastRow = Worksheets("Sheet1").Range("A4").End(xlDown).Row
Worksheets("Sheet1").Range("A5:D" & lastRow).Copy
Worksheets("Sheet4").Range("A7").PasteSpecial
End Sub

How to install external libraries to your Eclipse



We will download and install an external library "jsch.jar" as a practice here. Note that ".jar file" is a library which we are talking about. At first, we will download a .jar file. We will download jsch.jar here. This library is used to make, for example, a FTP program.

Access to this website.
http://www.jcraft.com/jsch/


You can download the jsch.jar file (not .zip file) and save it somewhere in your PC.

Now we will instaill the jar file to your Eclipse. Depending on your situation, there are two ways to install external libraries to your Eclipse. At frst, if you are making a new project with your Eclipse,

just name it and click Next.

Then you will see a display as below.
Click the "libraries". Then you can see "Add external Jars" on the left pane. Now click it.

Then you can choose a file to install. Choose the jsch-0.1.53.jar file which we downloaded just now.


If you already have a project, right-click on your project.
 You can see "Properties" at the bottom of the menu. Click the properties and you can "Java Build Path".
Click the Java Build Path.

Then choose the libraries and add external jar
Then you can choose your jar file. If your display shows the jar file as follows:
this means you've succeeded.

Saturday, October 3, 2015

Sample code: a method which gets the extension of a program

Sample code written in Java. This method gets what the program's extension is.


private static String getSuffix(String FileName) {
    if (FileName == null)
          return null;
       int point = FileName.lastIndexOf(".");
       if (point != -1) {
           return FileName.substring(point + 1);
       }
       return FileName;
   }

Thursday, October 1, 2015

Replacing letters

The result:

The code:
import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Finder1 { public static void main(String[] args) { String exampleString = "" + "haaa is \"${haaa}\"\n"+ "fooo is \"${fooo}\"\n"; Map<String, String> varmap = new HashMap<String, String>(); varmap.put("haaa", "HAAA"); varmap.put("fooo", "FOOO"); Pattern pattern = Pattern.compile("\\$\\{([^}]+)\\}"); // Replace once { Matcher m = pattern.matcher(exampleString); StringBuffer sb = new StringBuffer(exampleString.length()); if(m.find()){ m.appendReplacement(sb, varmap.get(m.group(1))); } m.appendTail(sb); System.out.println("---replaceOnce---"); System.out.println(sb.toString()); } // Replace all { Matcher m = pattern.matcher(exampleString); StringBuffer sb = new StringBuffer(exampleString.length()); while(m.find()){ m.appendReplacement(sb, varmap.get(m.group(1))); } m.appendTail(sb); System.out.println("---replaceAll---"); System.out.println(sb.toString()); } } }

Pattern finder and count how many times it is repeated

The program below finds a pattern and how many times it is repeated. This program returns a value "5" because there are 5 same patterns in the string data.


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Finder1 {

 public static void main(String[] args) {
         String s = "adapeuflbdasabababababadsapjsoa";
         Pattern p = Pattern.compile("ab");
         Matcher m = p.matcher(s);
         int count = 0;
         while (m.find()) {
             count++;
         }
         System.out.println(count);
     }
}