Saturday, November 28, 2015

the datagrid and the database

This is a GUI program which I made. By downloading it, you can see how the datagrid and the connection to a database work.

download: https://www.dropbox.com/s/xc1cut65xuzir2l/DatagridTest.zip?dl=0

code: download the file above and see inside the project.
This is a WPF program.



Wednesday, November 25, 2015

DB searcher

You can search a database file (accdb) in this Excel file. But maybe when you use this excel, you will see some warnings (because this file uses ADO to connect to the database). Please read carefully the warnings and enable the connection to the database to use this Excel.

Photo:


Download:
https://www.dropbox.com/s/mskm2h5gvv54bqb/DBsearch.zip?dl=0

Code:
See inside the Excel.

Monday, November 23, 2015

Open and delete a file (incomplete version) (server)

This program is a server program which receives commands from the client. See here for the client.

code:

import java.awt.Desktop;
import java.io.File;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class FileSearchServer{
public static void main (String args[]){
 try {
        // Create a new server socket that listens at port 8080
        ServerSocket ServerSocket1 = new ServerSocket(8080);
        System.out.println("Server is lisenting ... ");
        Socket socket1 = ServerSocket1.accept(); //accept a connection from client on port 8080

        OutputStream outputStream1 = socket1.getOutputStream();
        ObjectOutputStream objectOutputStream1 = new ObjectOutputStream(outputStream1);
        InputStream inputStream1 = socket1.getInputStream();
        ObjectInputStream objectInputStream1 = new ObjectInputStream(inputStream1);

        String rcv_path, send_msg, storewords2;
        String storewords1 = "";

        while(true) {
           // Recieve a message from client
           System.out.println("Waiting for client to respond ... ");
           rcv_path = (String)objectInputStream1.readObject();
           if(rcv_path != null &&  !(rcv_path.startsWith("del ")) && !(rcv_path.startsWith("open "))) {
          System.out.println("From Client : " + rcv_path);
            File file1 = new File(rcv_path);
       File[] files = file1.listFiles();
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US);

        for (int i = 0; i < files.length; i++){
         String mime = "";
        File file = files[i];
        System.out.println((i + 1) + ":    " + file + " *information is sent*");

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

        storewords2 = ((i + 1) + ":  " + file + "\nName:  "+ file.getName() + "\nLast modified time:  " + sdf.format(file.lastModified()) + "\nFile size:  " + getKB(file.length()) + " KB" + "\nMime type: " + mime);
        storewords1 = storewords1 + "\n" + storewords2 + "\n";
       }
            }else if( rcv_path != null && rcv_path.startsWith("del ")){
             System.out.println("From Client : " + rcv_path);
             String d_path = "";
             d_path = rcv_path.substring(4, (rcv_path.length()));
             File file1 = new File(d_path);
              if(file1.delete()){
               storewords1 = "Successfully deleted";
              } else{
               storewords1 = d_path + "\nThis file could not be deleted";
              }
            }else if( rcv_path != null && rcv_path.startsWith("open ")){
             System.out.println("From Client : " + rcv_path);
             String o_path = "";
             o_path = rcv_path.substring(5, (rcv_path.length()));
             File file1 = new File(o_path);
             Desktop desktop = Desktop.getDesktop();
             desktop.open(file1);
            }

           // Send a message to client
           System.out.print("\nTo Client : ");
           send_msg = storewords1;
           objectOutputStream1.writeObject(send_msg);
       }
     } catch(Exception e) {
        System.out.println(e);
     }
  }

 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;
 }
}

Open and delete a file (incomplete version) (client)

This program is a client program which sends commands to the server. See here for the server.

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

public class FileSearchClient {

 public static void main(String args[]) {
       try {
          Socket theSocket = new Socket("write local IP address here", 8080);
          System.out.println("Connected to server");

          InputStream inputStream = theSocket.getInputStream();
          ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
          OutputStream OutputStream = theSocket.getOutputStream();
          ObjectOutputStream objectOutputStream = new ObjectOutputStream(OutputStream);

          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();
             objectOutputStream.writeObject(send_msg);

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

Responding program (client)

See here for the server program.

Code:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class MyClient {
   public static void main(String args[]) {
      try {
         Socket theSocket = new Socket("write local IP address here", 8080);
         System.out.println("Connected to server");

         InputStream is = theSocket.getInputStream();
         ObjectInputStream ois = new ObjectInputStream(is);
         OutputStream os = theSocket.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);
      }
   }
}

Responding program (server)

This program receives commands from a client and responds certain messages, See here for the client.

Code:

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {
   public static void main(String args[]) {
      try {
         // Create a new server socket that listens at port 8080
         ServerSocket ServerSocket = new ServerSocket(8080);
         System.out.println("Server is lisenting ... ");
         Socket socket1 = ServerSocket.accept();//accept a connection from client on port 8080

         OutputStream outputStream1 = socket1.getOutputStream();
         ObjectOutputStream objectOutputStream1 = new ObjectOutputStream(outputStream1);
         InputStream inPutStream1 = socket1.getInputStream();
         ObjectInputStream objectInputStream1 = new ObjectInputStream(inPutStream1);

         String rcv_msg;
         while(true) {
            /* Recieve a message from client */
            System.out.println("Waiting for client to respond ... ");
            if((rcv_msg = (String)objectInputStream1.readObject()) != null) {
             if(rcv_msg.equals("What is your name?")){
              System.out.println("From Client : " + rcv_msg);
              System.out.print("\nTo Client : ");
                    objectOutputStream1.writeObject("My name is A.\n");
              continue;
             }else if(rcv_msg.equals("Song2")){
              System.out.println("From Client : " + rcv_msg);
              System.out.print("\nTo Client : ");
                    objectOutputStream1.writeObject("Woo-hooWoo-hoo\nWoo-hoo\nWoo-hoo");
              continue;
             }else if(rcv_msg.equals("What food do you like?")){
              System.out.println("From Client : " + rcv_msg);
              System.out.print("\nTo Client : ");
                    objectOutputStream1.writeObject("I like apples.\nWhat do you like to eat?\n");
              continue;
             }else{
              System.out.println("From Client : " + rcv_msg);
              System.out.print("\nTo Client : ");
                    objectOutputStream1.writeObject("Error.\n");
                    System.out.println("From Client : " + rcv_msg);
              continue;
             }
            }
         }
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}

open & delete file (client)

This is a client file. See the server here.

code:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

public class FileSearchClient {

 public static void main(String args[]) {
       try {
          Socket theSocket = new Socket("Write Local IP address here", 8080);
          System.out.println("Connected to server");

          InputStream inputStream = theSocket.getInputStream();
          ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
          OutputStream OutputStream = theSocket.getOutputStream();
          ObjectOutputStream objectOutputStream = new ObjectOutputStream(OutputStream);

          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();
             objectOutputStream.writeObject(send_msg);

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

open & delete file (server)

This server receives commands from a client and deal with files.

code:

import java.awt.Desktop;
import java.io.File;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class FileSearchServer{
public static void main (String args[]){
 try {
        // Create a new server socket that listens at port 8080
        ServerSocket ServerSocket1 = new ServerSocket(8080);
        System.out.println("Server is lisenting ... ");
        Socket socket1 = ServerSocket1.accept(); //accept a connection from client on port 8080

        OutputStream outputStream1 = socket1.getOutputStream();
        ObjectOutputStream objectOutputStream1 = new ObjectOutputStream(outputStream1);
        InputStream inputStream1 = socket1.getInputStream();
        ObjectInputStream objectInputStream1 = new ObjectInputStream(inputStream1);

        String rcv_path, send_msg, storewords2;
        String storewords1 = "";

        while(true) {
           // Recieve a message from client
           System.out.println("Waiting for client to respond ... ");
           rcv_path = (String)objectInputStream1.readObject();
           if(rcv_path != null &&  !(rcv_path.startsWith("del ")) && !(rcv_path.startsWith("open "))) {
          System.out.println("From Client : " + rcv_path);
            File file1 = new File(rcv_path);
       File[] files = file1.listFiles();
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US);

        for (int i = 0; i < files.length; i++){
         String mime = "";
        File file = files[i];
        System.out.println((i + 1) + ":    " + file + " *information is sent*");

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

        storewords2 = ((i + 1) + ":  " + file + "\nName:  "+ file.getName() + "\nLast modified time:  " + sdf.format(file.lastModified()) + "\nFile size:  " + getKB(file.length()) + " KB" + "\nMime type: " + mime);
        storewords1 = storewords1 + "\n" + storewords2 + "\n";
       }
            }else if( rcv_path != null && rcv_path.startsWith("del ")){
             System.out.println("From Client : " + rcv_path);
             String d_path = "";
             d_path = rcv_path.substring(4, (rcv_path.length()));
             File file1 = new File(d_path);
              if(file1.delete()){
               storewords1 = "Successfully deleted";
              } else{
               storewords1 = d_path + "\nThis file could not be deleted";
              }
            }else if( rcv_path != null && rcv_path.startsWith("open ")){
             System.out.println("From Client : " + rcv_path);
             String o_path = "";
             o_path = rcv_path.substring(5, (rcv_path.length()));
             File file1 = new File(o_path);
             Desktop desktop = Desktop.getDesktop();
             desktop.open(file1);
            }

           // Send a message to client
           System.out.print("\nTo Client : ");
           send_msg = storewords1;
           objectOutputStream1.writeObject(send_msg);
       }
     } catch(Exception e) {
        System.out.println(e);
     }
  }

 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;
 }
}

Data input & save & output (using a .txt file)


using System;
using System.Text;
using System.IO;
using System.ComponentModel;
using System.Windows.Forms;

public class Sample2 {
  public static void Main(string[] args) {
        bool isSecond = false;
        bool shouldStop = false;
        string path = "";
        string text = "";

        while(!shouldStop){

        try{
             if(!isSecond){
              Console.WriteLine("Prepare a .txt file to write on.");
              Console.WriteLine("Give me a directory for the .txt file.");
              Console.WriteLine("(Example: C:\\Users\\Documents\\aaa.txt)");
              Console.WriteLine("To stop this program, write [/stop] and hit the enter key.");
              path = Console.ReadLine();
             }
           
             if(path.Equals("/stop", StringComparison.CurrentCultureIgnoreCase)){
               break;
             }

           Encoding enc = Encoding.GetEncoding("Shift_JIS");
           //Shift JIS is for Japanese. Please change here depending on your language.
           StreamReader sr = new StreamReader(path, enc);
           text = sr.ReadToEnd();            

           sr.Close();
         
           Console.WriteLine("\nTo stop this program, write [/stop] and hit the enter key.");
           Console.WriteLine("If you want to open the .txt file, write [/open] and hit the enter key.");
           Console.WriteLine("If you want to check the inside of the ,txt file, write [/view] and hit the enter key.");
           Console.WriteLine("If you want to search for a certain word, write [/search] and hit the enter key");
           Console.WriteLine("Write some words to save in the .txt file:\n");

           StreamWriter writer = new StreamWriter(@path, true, enc);
           string word = Console.ReadLine();

             if(word.Equals("/stop", StringComparison.CurrentCultureIgnoreCase)){
               writer.Close();
               break;
             }else if(word.Equals("/open", StringComparison.CurrentCultureIgnoreCase)){
               writer.Close();
               System.Diagnostics.Process.Start(@path);
             
               isSecond = true;
               Console.WriteLine("Excuted.");
               continue;
             }else if(word.Equals("/search", StringComparison.CurrentCultureIgnoreCase)){
               writer.Close();
               Console.WriteLine("What word do you want to search for?");
               string searchWord = Console.ReadLine();
               Console.WriteLine(searchWord + " is being searched for..");
             
               System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(
               @searchWord,
               System.Text.RegularExpressions.RegexOptions.IgnoreCase);
             
               System.Text.RegularExpressions.Match m = r.Match(text);
             
               int count = 0;
               while (m.Success){
                   count++;
                   m = m.NextMatch();
               }
             
               Console.WriteLine("The word " + searchWord + "appreas " + count + " times in the .txt file.");
               isSecond = true;
               continue;
             }else if(word.Equals("/view", StringComparison.CurrentCultureIgnoreCase)){
                 writer.Close();
                 Console.WriteLine("Saved data: \n" + text + "\n");
                 isSecond = true;
                 continue;
             }    
   
           writer.WriteLine(word);
           Console.WriteLine("Saved");

           writer.Close();
           isSecond = true;
         
           }catch(FileNotFoundException){
             Console.WriteLine("File not found");
            return;
           }catch(Win32Exception){
             Console.WriteLine("File not found");
             return;
           }catch(IOException){
             Console.WriteLine("IOException");
             return;
           }catch(NotSupportedException){
             Console.WriteLine("NotSupportedException");
             return;
           }catch(ArgumentException){
             Console.WriteLine("ArgumentException");
             return;
           }
         }

        Console.WriteLine("Program terminated");
          if(isSecond){  
            Console.WriteLine(".txt file will be opened.");
            System.Diagnostics.Process.Start(@path);
          }
        return;
  }
}

Sun rise


two angels



The original concept is William Adolphe Bouguereau's L'Amour et Psyché, enfants.

a woman who is thinking


a dog


Sunday, November 22, 2015

How to change the format of currency-typed data

With the VBA editor, you can change the format of currency-typed data.

Open up the VBA editor and write as follows:

Sub Test()
Worksheets("Sheet1").Columns("A").NumberFormatLocal = "#,##0 ""RS"""
End Sub

RS is a currency of India. If you execute this macro, all of the data of A-column of Sheet1 will be displayed as follows:
All data of A-column is displayed in this format

If you want to designate a format for the data which are less than 0, write as follows:

Sub Test()
Worksheets("Sheet1").Columns("A").NumberFormatLocal = "#,##0 ""euro"";[Red]#,##0 ""euro"""
End Sub


The two formats are divided by ";". If you excute this macro, all data which are less than 0 is displayed in red:


How to make a GUI program with C#

Today, I will explain how to make a Graphical User Interface (GUI) program with C#. We will make a simple program with a button.

Go to microsoft's website to download for Integrated Development Environment called Visual Studio:
https://www.visualstudio.com/vs/

Visual Studio community version is a free & useful IDE for C#. Please note, Enterprise version and Professional version are not free but only community version is free.
(Actually not only for C#. Visual Studio can be used to develop other language's programs like C, C++, Visual Basic and so on).


After downloading the Visual Studio, start it. You will be asked to log into your Microsoft account. Log in with your information.

After logging in, Start page like below will show up. Choose "File" --> "New" --> "Project".


A window like below will show up now. Choose "Visual C#" --> "WPF application". You can name it as you like, so you can use the default name "WpfApplication1" as it is. I named it as "WpfApplication2" because WpfApplication1 is already existing. By the way, this style of capitalization is called "PascalCasing". See here for the design detail.

Then this window like below will show up. This is the place where you fix and edit your program design.You will define how the program will look like here. We will add a button to our program.


Choose "button" from the toolbox and drag & drop it in the window as follows:


After adding the button, double-click the button on the window.

You will be brought to a window where you write codes for the program. You will define what your program will do. (not for design now!) There are two sections; one is named MainWindow(), and the other is button_click(). "MainWindow()" is a constructor, which is called everytime the program starts, so usually codes for initialization are written here.

Second one "button_click()" is a method. Method is used to define a certain routine that produces a certain return. This is called "Function" in C or C++. This "button_click" method defines what will happen when the button is clicked.

Write "MessageBox.Show("Hello World!!");" inside button_click() method as follows:

MassageBox.Show("Anything to show inside the message box") is also a method, but this method is called from other place of the program and is prepared from the beginning automatically by the visual studio. What you need to do to use this MessageBox.show is just call it like above.

After writing the code, click "Start" from the menu bar.

Then your program will appear....


Click the button at the center. You will see the Message box you defined.




Sunday, November 15, 2015

How to start C# programming

C# is a programming language which is very similar to Java and is useful to make an application which is relating to .NET Framework.
.NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs primarily on Microsoft Windows.-Wikipedia .Net framework
Here we will learn how to prepare for programming with C#.

We suppose that you are using windows 7 OS. At first, we must set the environment variable for C#. Open your explorer then move as follows:
Start --> Computer -->  Windows --> Microsoft.NET --> Framework (if you are using OS 64bit version, choose Framework64) --> (choose the latest version like "v4.0")

Then copy the path as follows:


When you've done copying it, we will move to "Environment Variables" as follows:
Start --> Right-Click on Computer --> Properties --> Advanced system settings --> Environment Variables



Then look for Environment variables and click it.

You will see the following window. If there is an item called "PATH", edit it. If you don't find "PATH", click "new" button and make a item named "PATH" in the user variable pane.
If you've clicked "Edit", add the path of Microsoft.NET's framework which you have copied. Please add ";" in the end of the path unless ";" is already there:
example: ;C:\Windows\Microsoft.NET\Framework64\v4.0.30319
or
C:\Windows\Microsoft.NET\Framework64\v4.0.30319


like this

Then click "OK".

If you've clicked "New", name it as "PATH" then add the path without adding anything. If you've clicked "New", you don't need to put anything in front of the path.
example: C:\Windows\Microsoft.NET\Framework64\v4.0.30319

add this path to Environment Variables.

When you've done this, click "OK".

Now you can use C#'s command on CMD.

We will check if the new environment variable is working. Open your CMD. Then write as follows:
csc
Then push the enter on your physical keyboard.

If you see this Microsoft's message and "warning CS2008"(plus some message) and "error CS1562"(plus some message), that means you've succeeded the environment variable setting.

When you create a C# program, use this "csc" command after moving to the folder which has the .cs file:
csc Sample.cs
Then you can create a .exe file if there aren't any errors in the source file.

To move to the targeted folder, use cd command:
cd C:\Users\Documents\C#

like this

You must be at the folder which contains the targeted C#'s source file to use the csc command, which create the .exe file from the C#'s source file.

Tuesday, November 10, 2015

Painting: sea


Save & output using a .txt file

using System;
using System.Text;
using System.IO;

public class Sample2 {
  public static void Main(string[] args) {
        bool isSecond = false;
        string path ="";

        while(true){

          if(!isSecond){
            Console.Write("Give me a path for the text file.\n");
            path = Console.ReadLine();
          }

        Encoding enc = Encoding.GetEncoding("Shift_JIS");
        StreamReader sr = new StreamReader(path, enc);
        string text = sr.ReadToEnd();

        sr.Close();

        Console.Write("Saved data: \n" + text);

        Console.Write("To stop this program, write [/stop].\nWrite something: \n");

        StreamWriter writer = new StreamWriter(@path, true, enc);
        string word = Console.ReadLine();
              if(word.Equals("/stop") || word.Equals("/Stop")){
                break;
              }    
     
        writer.WriteLine(word);
        Console.Write("Saved it\n");

        writer.Close();
        isSecond = true;

        }
      Console.Write("Program successfully stopped.\nThe text file will be opened.\n");
      System.Diagnostics.Process.Start(@path);
      return;
  }
}

Monday, November 9, 2015

Word counter

Oddly enough, the name is player but this doesn't play anything. I named it a Player for no reason.

This is a GUI which counts how many times a word is repeated in a .txt file.

You need to previously prepare a .txt file to search.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JScrollPane;

public class Player extends JFrame{

  /**
  *
  */
  private static final long serialVersionUID = 1L;
  private JTextField textField;
  private JTextArea textArea;
  private final Action action_1 = new Filechoose();
  JFrame frame;
  private final Action action = new Go();
  private String pathA = "";
  private JTextField textField_1;
  public static void main(String[] args){
 

    Player frame = new Player();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBounds(10, 10, 500, 300);
    frame.setTitle("Word counter");
    frame.setVisible(true);
  }

  Player(){

    JPanel textPanel = new JPanel();
    pathA = "";
 
    getContentPane().add(textPanel, BorderLayout.CENTER);
    textPanel.setLayout(null);
 
    JButton Go = new JButton("Go");
    Go.setAction(action);
    Go.setBounds(45, 231, 91, 21);
    textPanel.add(Go);
 
    textArea = new JTextArea();
    textArea.setBounds(35, 75, 365, 139);

 
    textField = new JTextField();
    textField.setBounds(35, 10, 303, 19);
    textPanel.add(textField);
    textField.setColumns(10);
 
    JButton choose = new JButton("C");
    choose.setAction(action_1);
    choose.setBounds(350, 11, 50, 21);
    textPanel.add(choose);
 
    textField_1 = new JTextField();
    textField_1.setBounds(35, 46, 96, 19);
    textPanel.add(textField_1);
    textField_1.setColumns(10);
 
    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setBounds(35,75,365,139);
    textPanel.add(scrollPane);
  }

 private class Filechoose extends AbstractAction {
  private static final long serialVersionUID = 1L;
  public Filechoose() {
            putValue(NAME, "C"); //Name
            putValue(SHORT_DESCRIPTION, "Some short description");
        }
        public void actionPerformed(ActionEvent e) {
            JFileChooser filechooser = new JFileChooser(); // Class for choosing a file

            int selected = filechooser.showOpenDialog(frame); //dialogue for getting the file path
            if (selected == JFileChooser.APPROVE_OPTION){
                File file = filechooser.getSelectedFile();
                textField.setText(file.getPath());
                textArea.append("Chosen: " + file.getName() + "\n");
                pathA = file.getPath();
             }
        }
    }
 
 private class Go extends AbstractAction {
  private static final long serialVersionUID = 1L;
  public Go() {
   putValue(NAME, "Go"); // Name
   putValue(SHORT_DESCRIPTION, "Some short description");
  }
 
  public void actionPerformed(ActionEvent e) {
   try {
    textArea.setText("");
    File file1 = new File(pathA);
       Scanner scan;
    scan = new Scanner(file1);
    scan.useDelimiter("\\r\\n");
    int count = 0;
    int count2 = 0;
    String strF = "";
    textArea.append("Your word is '" + textField_1.getText() + "'.\n");
   
    while(scan.hasNext()) {
     count2++;
        String str2 = scan.next();
        String str3 = textField_1.getText();
        Pattern pattern1 = Pattern.compile(str3);
            Matcher m = pattern1.matcher(str2);
         
             while(m.find()){
                 count++;
                 String strF2 = "";
              strF2 = "Line "+ count2 + "\n";
              strF = strF + strF2;
             }
    }
    textArea.append("This word is " + count + " times repeated in this file.\n");
    textArea.append("Found line: \n" + strF);
    scan.close();
   } catch (FileNotFoundException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }

  }
 }
}

Data input and save and output (using a .txt file)

I don't know how to close the external application so it keeps open...

This is incomplete version but there is a complete version.
code:

using System;
using System.Text;
using System.IO;
public class Sample2 {
  public static void Main(string[] args) {
        bool isSecond = false;
        string path ="";
        while(true){
         if(!isSecond){
          Console.Write("Give me a path for the text file.\n");
          path = Console.ReadLine();
         }
        Encoding enc = Encoding.GetEncoding("Shift_JIS");
        StreamReader sr = new StreamReader(path, enc);
        string text = sr.ReadToEnd();
        sr.Close();
        Console.Write("Saved data: \n" + text);
        Console.Write("Write something: \n");
        System.Diagnostics.Process.Start(@path);
   
        StreamWriter writer = new StreamWriter(@path, true, enc);
        string word = Console.ReadLine();    
   
        writer.WriteLine(word);
        Console.Write("Saved it\n");
        writer.Close();
        isSecond = true;
        }
  }
}

Nice websites to learn Java

www.compilejava.net
For the practice for Java programming.

Code academy
Very good website to learn basics of Java.
There are other languages, too. Like Ruby.

Coding bat
Good website to improve your Java skill.

Home and learn
Good website for biginners of Java.



Saturday, November 7, 2015

Circle calculator

Putting a value of radius, this program calculates the diameter and the area of the circle.
code:

using System;
public class Sample1 {
  public static void Main(string[] args) {
        while(true){
        Console.Write("The radius of circle?: ");
        double radius = double.Parse(Console.ReadLine());
        double diameter = radius * 2;
        double area = radius * radius * Math.PI;
 Console.Write("Diamiter: {0}\nArea: {1}\n", diameter, area);
        }
  }
}

Get the maximum & minimum value

This program gets the maximum & minimum value.

code:

using System;
public class Sample{
  public static void Main(string[] args){
    Console.Write("Input how many numbers you want to compare: ");
 
    int m = int.Parse(Console.ReadLine());
 
    int m2 = m;
    int[] n = new int[m];  
    for(int i=0; i<m; i++){
    n[i] = int.Parse(Console.ReadLine());
    }

    int max = n[0];
    int min = n[0];
    for(int i=0; i<m; i++){
      if(n[i]>max){
      max = n[i];
      }
      if(n[i]<min){
      min = n[i];
      }
     }
      Console.Write("the biggest number: {0} \nthe smallest number: {1}\n", max, min);  
  }
}

Wednesday, November 4, 2015

Sample code: Saving & Fetching data from a database

This is a small program which saves and fetches data from a database. I used "ucanaccess" and "JDatepicker" to make this program. Please check below for the detail.


Please make sure that you have a MSaccess inside the same folder.

download:
https://www.dropbox.com/s/bue8dhliydibchh/DatebaseTest.zip?dl=0

Code:

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;

import org.jdatepicker.impl.JDatePanelImpl;
import org.jdatepicker.impl.JDatePickerImpl;
import org.jdatepicker.impl.UtilDateModel;

import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Properties;
import java.util.Locale;

import javax.swing.Action;

public class DatebaseTestMain extends JFrame {

 /**
  *
  */
 private static final long serialVersionUID = 1L;
 private JPanel contentPane;
 private JTextField textField_1;
 private JLabel lblCategory;
 private JTextField textField_2;
 private JLabel lblExpenseFor;
 private JTextField textField_3;
 private JLabel lblAmount;
 private JTextField textField_4;
 private JLabel lblReceiptNumber;
 private JButton btnAddInfo;
 private final Action action = new SwingAction();
 private JTextArea textArea;
 private JTextArea txtrDisprset;
 private final Action action_1 = new SwingAction_1();
 private JDatePickerImpl datePicker;
 private JLabel lblNewLabel_1;
 private String pathOfThisProgram;
 

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

 /**
  * Create the frame.
  */
 public DatebaseTestMain() {
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setBounds(100, 100, 450, 531);
 
  contentPane = new JPanel();
  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
  setContentPane(contentPane);
  contentPane.setLayout(null);
 
  JLabel lblNewLabel = new JLabel("Date");
  lblNewLabel.setBounds(12, 24, 50, 13);
  contentPane.add(lblNewLabel);
 
  textField_1 = new JTextField();
  textField_1.setBounds(12, 111, 113, 19);
  contentPane.add(textField_1);
  textField_1.setColumns(10);
 
  lblCategory = new JLabel("Category");
  lblCategory.setBounds(12, 88, 75, 13);
  contentPane.add(lblCategory);
 
  textField_2 = new JTextField();
  textField_2.setBounds(12, 175, 113, 19);
  contentPane.add(textField_2);
  textField_2.setColumns(10);
 
  lblExpenseFor = new JLabel("Expense for");
  lblExpenseFor.setBounds(12, 152, 75, 13);
  contentPane.add(lblExpenseFor);
 
  textField_3 = new JTextField();
  textField_3.setBounds(232, 47, 113, 19);
  contentPane.add(textField_3);
  textField_3.setColumns(10);
 
  lblAmount = new JLabel("Amount");
  lblAmount.setBounds(232, 24, 91, 13);
  contentPane.add(lblAmount);
 
  textField_4 = new JTextField();
  textField_4.setBounds(232, 111, 113, 19);
  contentPane.add(textField_4);
  textField_4.setColumns(10);
 
  lblReceiptNumber = new JLabel("Receipt Number");
  lblReceiptNumber.setBounds(232, 88, 113, 13);
  contentPane.add(lblReceiptNumber);
 
  textArea = new JTextArea();
 
  JScrollPane scrollPane1 = new JScrollPane(textArea);
     scrollPane1.setBounds(242, 173, 178, 67);
     contentPane.add(scrollPane1);
 
  JLabel lblRemarks = new JLabel("Remarks");
  lblRemarks.setBounds(232, 152, 101, 13);
  contentPane.add(lblRemarks);
 
  btnAddInfo = new JButton("Add Info");
  btnAddInfo.setBounds(53, 219, 91, 21);
  btnAddInfo.setAction(action);
  contentPane.add(btnAddInfo);
 
  txtrDisprset = new JTextArea();
  txtrDisprset.setText("");
 
  JScrollPane scrollPane = new JScrollPane(txtrDisprset);
     scrollPane.setBounds(34, 320, 364, 114);
     contentPane.add(scrollPane);
   
     JButton btnFetchData = new JButton("Fetch data");
     btnFetchData.setAction(action_1);
     btnFetchData.setBounds(32, 449, 137, 21);
     contentPane.add(btnFetchData);

     UtilDateModel model = new UtilDateModel();
     //model.setDate(20,04,2014);
     // Need this...
     Properties p = new Properties();
     p.put("text.today", "Today");
     p.put("text.month", "Month");
     p.put("text.year", "Year");
     JDatePanelImpl datePanel = new JDatePanelImpl(model, p);
     // Don't know about the formatter, but there it is...
     datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter());
     datePicker.setDoubleClickAction(true);
     datePicker.setSize(178, 30);
     datePicker.setLocation(12, 48);
     contentPane.add(datePicker);
     datePicker.setTextEditable(true);
   
     lblNewLabel_1 = new JLabel("...");
     lblNewLabel_1.setBounds(181, 453, 251, 13);
     contentPane.add(lblNewLabel_1);
   
     JLabel lblDisplaytheformat = new JLabel("ID : Expensefor : Category : Amount : Receipt number : Remarks");
     lblDisplaytheformat.setBounds(34, 297, 364, 13);
     contentPane.add(lblDisplaytheformat);
     pathOfThisProgram = getCurrentDir();
 }
 
 public class DateLabelFormatter extends AbstractFormatter {
     private String datePattern = "yyyy-MM-dd";
     private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);

     @Override
     public Object stringToValue(String text) throws ParseException {
         return dateFormatter.parseObject(text);
     }

     @Override
     public String valueToString(Object value) throws ParseException {
         if (value != null) {
             Calendar cal = (Calendar) value;
             return dateFormatter.format(cal.getTime());
         }
         return "";
     }

 }
 
 private class SwingAction extends AbstractAction implements Runnable{
  /**
   *
   */
  private static final long serialVersionUID = 1L;

  public SwingAction() {
   putValue(NAME, "Add Info");
   putValue(SHORT_DESCRIPTION, "Some short description");
  }
 
  public void actionPerformed(ActionEvent e) {
   SwingAction tt = new SwingAction();
   Thread t = new Thread(tt);
   t.start();
  }
 
  public void run(){
   try{
    if(textField_3.getText().equals("") || !datePicker.getModel().isSelected()){
     JOptionPane.showMessageDialog(contentPane, "[Date] and [Amount] are essential.");
     return;
    }
    pathOfThisProgram = getCurrentDir();
    lblNewLabel_1.setText("Saving the data...");
    Connection conn
    = DriverManager.getConnection("jdbc:ucanaccess://"
      + pathOfThisProgram + "\\CompInfo.accdb");
   
    Statement statement = conn.createStatement();
   
    int day = datePicker.getModel().getDay();
    int month = datePicker.getModel().getMonth() + 1;
    //month-number starts from 0. So I must add 1 to the month number to make it precise.
    int year = datePicker.getModel().getYear();
   
    String str = year + "-" + month + "-" + day  + " 00:00:00";
   
    statement.executeUpdate("INSERT INTO ExpenseTable (Date1, Category, Expensefor, Amount, ReceiptNum, Remarks)"
      + " VALUES "
      + "('" + str + "',"
       + "'" + textField_1.getText() + "',"
          + "'" + textField_2.getText() + "',"
       + "'" + textField_3.getText() + "',"
       + "'" + textField_4.getText() + "',"
       + "'" + textArea.getText() + "');");
   
    statement.close();
    conn.close();
    lblNewLabel_1.setText("Succefully finished.");
   }catch(SQLException ex){
    System.err.print(ex);
    JOptionPane.showMessageDialog(contentPane, "Error happened. Please make sure this program and the datebase are inside the same folder.");
   }
 
  }
 }
 
 public static String getCurrentDir() {
        String path = new File(".").getAbsoluteFile().getParent();
    return path;
 }
 
 private class SwingAction_1 extends AbstractAction implements Runnable{
  /**
   *
   */
  private static final long serialVersionUID = 1L;

  public SwingAction_1() {
   putValue(NAME, "Show me the data");
   putValue(SHORT_DESCRIPTION, "Some short description");
  }
  public void actionPerformed(ActionEvent e) {
   txtrDisprset.setText("");
   SwingAction_1 tt1 = new SwingAction_1();
   Thread t1 = new Thread(tt1);
   t1.start();
  }
 
  public void run(){
   try{
   pathOfThisProgram = getCurrentDir();
   lblNewLabel_1.setText("Fetching the data...");
   Connection conn = DriverManager.getConnection("jdbc:ucanaccess://"
     + pathOfThisProgram + "\\CompInfo.accdb");
   Statement s = conn.createStatement();
   ResultSet rs = s.executeQuery("SELECT ExpenseTable.* FROM ExpenseTable ORDER BY ID;"); //Query

   ArrayList<Integer> ID = new ArrayList<Integer>();
   ArrayList<String> Date1 = new ArrayList<String>();
   ArrayList<String> Expensefor = new ArrayList<String>();
   ArrayList<String> Category = new ArrayList<String>();
   ArrayList<String> Amount = new ArrayList<String>();
   ArrayList<String> ReceiptNum = new ArrayList<String>();
   ArrayList<String> Remarks = new ArrayList<String>();
   
   SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd", Locale.JAPAN);

   int count = 0;
    while (rs.next()) {
     ID.add(rs.getInt(1));
     Date1.add(sdf1.format(rs.getDate(2))); //Fetch data from the DB. Column-number starts from 1.
     Expensefor.add(rs.getString(3) + " ");
     //Column number depends on the order of creating. Changing the column-location doesn't affect the column-number.  
     Category.add(rs.getString(4) + " ");
     Amount.add(getWage(rs.getString(5)) + " ");
     ReceiptNum.add(rs.getString(6));
     Remarks.add(rs.getString(7));
     
     count++;  //Count how many times it is repeated
    }
   
    for(int i=0; i < count; i++){
     txtrDisprset.append(ID.get(i) + " : ");
     txtrDisprset.append(Date1.get(i) + " : ");
     txtrDisprset.append(Expensefor.get(i) + " : ");
     txtrDisprset.append(Category.get(i) + " : ");
     txtrDisprset.append(Amount.get(i)  + "dollar" + " : ");
     txtrDisprset.append(ReceiptNum.get(i) + " : ");
     txtrDisprset.append(Remarks.get(i) + "\n");
    }
   lblNewLabel_1.setText("Successfully finished.");
   }catch( SQLException e ){
    System.err.print(e);
    lblNewLabel_1.setText("Error happened. Please make sure this program and the datebase are inside the same folder.");
   }
  }
 }
 private static String getWage(String n){
       int point = n.lastIndexOf(".");
       if (point != -1) {
           return n.substring(0, point);
       }
       return n;
 }
}