Thursday, May 30, 2013

Java basic

1. in one .java file, there could be as many class as you wish, but there should be at most 1 public class, and this class name should be the same with the file name.

// B.java

class A

{
}

public class B

{
}

class C

{
}

2. for boolean, there are only true and false, no -1, 0,1
in C++, you can write like this:

while(1)

{
}

but in Java, while(1) is wrong, and you can only use:
while (true)

{
}


3. define array
//-1

int num[];

num=new int[3]; //ok;

int num[]=new int[3];//ok

int num[]={1,2,3};//ok

int num[]=new int[]{1,2,3};//ok

int num[]=new int[3]{1,2,3};//error

int num[3]; //error



//-2

int [][] num;

num=new int[2][];

num[0]=new int[3]; //3 elements

num[1]=new int[4]; //4 elements



4. for loop
for(int i=0; i<5; i++)

{
   int a=i; //ok

}

int b=i;// error, i is not defined out of the for loop

5. print hex number
  int hx=0xffffffff;
  int hc=hx<<2;
  System.out.println(Integer.toHexString(hc));
6. default value
int   0;

char '\0'

boolean false

object  null

7.  same name for parameter and member
class Point

{
    int x,y;

    void func1(int x, int y)

   {

      x=x; //parameter to parameter, not what we want

      y=y; //parameter to parameter, not what we want

   }

  

    void func2(int x, int y)

   {

      this.x=x; //parameter x to member x

      this.y=y; //parameter y to member y

   }



}
8. call another construction method
 class Point

{
    int x,y;

    Point(int a, int b)

  {

     x=a;

     y=b;

  }



  Point()

 {

    this(3,4);// call another construct method, and should be the first statement

 }

}

9. static
static methods could call static methods and access the static variable, could not call the non-static methods or access variable;
while  non-static methods  could call static methods and access to static variable.
10.. final variable

In most cases, the final variable should be initialized when it is defined.
class Point

{

    final double PI=3.1415926;

}



one exception:

class Point

{

    final double PI;

    Point()

  {

     PI=3.1415926; 

  }

}

however, if the final variable is also static, you must initialize it when defining it:
static final double PI=3.1415926;

11. call parent method

public class MyAnimal
{
   MyAnimal()
  {
       System.out.println("I am Animal! without parameter");
  }

     MyAnimal(int param)
  {
       System.out.println("I am Animal! with parameter");
  }

}


 class MyFish extends MyAnimal
{

      public MyFish()
   {
      // in this place, super()is called even if you do not write it;

     // so if there is no MyAnimal() at all, error would happen.

     // in that case, you could use  super(0) if  MyAnimal(int param) is defined

     // or you could redifine the MyAnimal() 

      System.out.println("I am fish! without parameter");
   }

    public MyFish(int param)
   {
      //in this place, still super(),not super(0), is called even if you do not write it;

     // to call MyAnimal(int param), should write super(0) in this place

     // 0 represents the parameter, you can use anyone you like
      System.out.println("I am fish! with parameter!");
 
 } 

    public void breathe()
    {
          super. breathe(); // use this call  parent  breathe();

          System.out.println("Fish breathe!");

    }

}
12. polymorphic

class Parent
{
    void fun1()
  {
     System.out.println(" Parent 1");
  }
   void fun2()
  {
     System.out.println(" Parent 2");
  }
}

class Child extends Parent
{
  
   void fun1()
  {
     System.out.println(" Child 1");
  } 
  public static void main(String[] args)
 {
       Child cd=new Child();
       Parent pt=cd;//Ok
       pt.fun1();    // result: Child 1, because of new Child();
       pt.fun2();    // result: Parent 2, because Child dose not override fun2()

       Parent pt1=new Parent();//Ok
       Child cd1=pt1;//error, can not convert from Parent to Child
 }
}


Wednesday, May 29, 2013

read and write file in Java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Read_Write {

 public static void main(String[] arg) throws IOException{
 String fileName = "data/input/tweet_2012_06";
 BufferedReader in = new BufferedReader(new FileReader(fileName));
 String str;

 FileWriter fstream = new FileWriter("data/output_tweet_2012_06.txt");
 BufferedWriter out = new BufferedWriter(fstream);

 int counter = 0;
 while ((str = in.readLine())!= null){
  System.out.println(counter+"  " + str);
  out.write(str);
  counter++;

 }
    System.out.println("counter is "+counter);
  out.close();
 in.close();
 }
}

SendMessage from modaless dialog to the view in SDI without document/view structure support--another method

I create one SDI without document/view structure support, i name the project as ImagePro, then I can get the following files:

ChildView.cpp; (class CChildView : public CWnd, OnPaint() is here)
MainFrm.cpp; (class CMainFrame : public CFrameWnd)
ImagePro.cpp;(class CImageProApp : public CWinApp)

I also create CModalLessDlg using the dialog template, which is defined in ModalLessDlg.cpp and ModalLessDlg.h

In the  ModalLessDlg.cpp, I want to press the "Begin" button to send the "view" a message

you can realize it like this:

1. in ChildView.cpp
#include "ModalLessDlg.h"

void CChildView::OnModalLess() // show the modalless dialog
{

    CModalLessDlg* instance = new CModalLessDlg(this);
    instance->Create(CModalLessDlg::IDD,this);
    instance->PARENT = this;  
    instance->ShowWindow(1);

}


2. in ModalLessDlg.h

#include "ChildView.h"



public:

CChildView *PARENT;



3. in ChildView.h

public:

void     setDisplayText(CString src);

private:

CString   displayText;


4. in ChildView.cpp

CChildView::CChildView(): displayText(_T("zhiguang"))
{
}



void CChildView::setDisplayText(CString src)
{
    displayText=src;
    Invalidate(TRUE);
}



void CChildView::OnPaint() // show different results of image 
{


  CPaintDC dc(this); // device context for painting   
  CRect rect;
  GetClientRect (&rect);
  dc.DrawText (displayText, -1, &rect,DT_SINGLELINE | DT_CENTER | DT_VCENTER);

}



5. in ModalLessDlg.cpp

void CModalLessDlg::OnBegin() // 
{

  CString str_sent="OnBegin is running!";
  PARENT->setDisplayText(str_sent);
}




that is all.

it is using ChildView as one parameter to construct the modaless dialog, then you can easily use the ChildView and its members to change the client area.



Tuesday, May 28, 2013

SendMessage from modaless dialog to the view in SDI without document/view structure support

I create one SDI without document/view structure support, i name the project as ImagePro, then I can get the following files:

ChildView.cpp; (class CChildView : public CWnd, OnPaint() is here)
MainFrm.cpp; (class CMainFrame : public CFrameWnd)
ImagePro.cpp;(class CImageProApp : public CWinApp)

I also create CModalLessDlg using the dialog template, which is defined in ModalLessDlg.cpp and ModalLessDlg.h

In the  ModalLessDlg.cpp, I want to press the "Begin" button to send a text to the "view"

you can realize it like this:

1. in MainFrm.h, there is one protected variable:

protected: CChildView   m_wndView;


change it as public variable:

public: CChildView   m_wndView;


2. in ModalLessDlg.cpp:

#define WM_MY_DOSOME (WM_USER+1)


3. in ModalLessDlg.cpp:

void CModalLessDlg::OnBegin() // 
{
 // TODO: start
    
  CMainFrame   *pFrame=(CMainFrame*)(AfxGetApp()->m_pMainWnd); 
  char buf[]="I LOVE YOU";
 (pFrame->m_wndView).SendMessage(WM_MY_DOSOME,(WPARAM)buf,0);

}


4. In ChildView.h, add the following:

afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam);//before DECLARE_MESSAGE_MAP()


5. in ChildView.cpp, add the following:

BEGIN_MESSAGE_MAP(CChildView, CWnd)
 // ...
    ON_MESSAGE(WM_MY_DOSOME,OnMyMessage)  //only need to add this line

 //...
END_MESSAGE_MAP()



//then realize the response function:

LRESULT CChildView::OnMyMessage(WPARAM iParam1,LPARAM iParam2)
{
   
 char *buf=(char *)iParam1; 
 CString str;
 str.Format("%s",buf);
 MessageBox(str);
 return 0L;

}


the function is only a test to see whether you can receive the text or not, you can also show it in the client area of the view through Invalidate() again in this OnMyMessage function.



modaless dialog refresh the view in SDI without document/view structure support

I create one SDI without document/view structure support, i name the project as ImagePro, then I can get the following files:

ChildView.cpp; (class CChildView : public CWnd, OnPaint() is here)
MainFrm.cpp; (class CMainFrame : public CFrameWnd)
ImagePro.cpp;(class CImageProApp : public CWinApp)

I also create CModalLessDlg using the dialog template, which is defined in ModalLessDlg.cpp and ModalLessDlg.h

In the  ModalLessDlg.cpp, I want to press the "Begin" button to refresh the "view"

you can realize this like this:

1. in MainFrm.h, there is one protected variable:

protected: CChildView   m_wndView;

change it as public variable:

public: CChildView   m_wndView;

2. add one public variable for the ChildView.h:

public: int dlg_fresh;

initialize it in ChildView.cpp:

CChildView::CChildView()
{
 dlg_fresh=0;
}

3. in the response function of modalless dialog button, write like this:

//ModalLessDlg.cpp 

void CModalLessDlg::OnBegin() // stard the thread
{
 CMainFrame   *pFrame=(CMainFrame*)(AfxGetApp()->m_pMainWnd); // get the mainframe
 (pFrame->m_wndView).dlg_fresh=1; //set the flag
 (pFrame->m_wndView).Invalidate(); // refresh the view in the ChildView

}

4. in the ChildView.cpp, implement the OnPaint() like this:

//ChildView.cpp

void CChildView::OnPaint()
{
 CPaintDC dc(this); // device context for painting
 CRect rect;
 GetClientRect (&rect);
 if(dlg_fresh==0)
 {
  dc.DrawText (_T ("it is not the modaless dlg refreshing!"), -1, &rect,DT_SINGLELINE | DT_CENTER | DT_VCENTER); 
 }
 else
 {
    dc.DrawText (_T ("it is the modaless dlg refreshing!"), -1, &rect,DT_SINGLELINE | DT_CENTER | DT_VCENTER); 
       dlg_fresh=0;
 }
}


Monday, May 27, 2013

kernel event object and thread in MFC

one button to create the kernel event object and worker thread, and the other button to signal the event and terminate the thread.



UINT __cdecl MyThreadProc(LPVOID lpParameter) // thread generation function
{
   CEvent* pEvent = (CEvent*)(lpParameter);
   VERIFY(pEvent != NULL);
   // Wait for the event to be signaled
   ::WaitForSingleObject(pEvent->m_hObject, INFINITE);
   // Terminate the thread
   ::AfxEndThread(0, FALSE);
   return 0L;
}


void CModalLessDlg::OnBnClickedButton1() // start the thread
{
 // TODO: start
   pEvent = new CEvent(FALSE, FALSE);
   // Create a thread that will wait on the event
   //CWinThread* pThread;
   pThread = ::AfxBeginThread(&MyThreadProc, pEvent, 0, 0, CREATE_SUSPENDED, NULL);
   pThread->m_bAutoDelete = FALSE;
   pThread->ResumeThread();
  
   // show the status of thread
   CString st1="Thread started";
   SetDlgItemText(IDC_EDIT1, st1);
}


void CModalLessDlg::OnBnClickedButton2() // setevent and terminate the thread
{

    pEvent->SetEvent();
   // Wait for the thread to consume the event and return
    ::WaitForSingleObject(pThread->m_hThread, INFINITE);
    delete pThread;
    delete pEvent;
 // show the status of thread
    CString st2="Thread Terminated!";
    SetDlgItemText(IDC_EDIT1, st2);
}

edge detection based on sobel operator in MFC

void CChildView::OnEdge() // edge detection based on Sobel operators
{

 {
 int operx[3][3]={-1,0,1,-2,0,2,-1,0,1};//Sobel operators
 int opery[3][3]={1,2,1,0,0,0,-1,-2,-1};//Sobel operators
 int i,j;
 int p=0;
 int smx=0,smy=0;
 //CImage img_tem;
 //img_tem.Create(img_width,img_hight,24,0);
 for(i=0;i<img_hight;i++)
 {
  for(j=0;j<img_width;j++)
  {
   COLORREF cf = MyRGB(0,0,0);
   img_final.SetPixel(j,i,cf); //img_final is a member of this class, this is to reset it to zeros
         
  }
 }

 for(i=0;i<img_hight-2;i++)
 {
  for(j=0;j<img_width-2;j++)
  {
            smx=0;
   smy=0;
   for (int m=0; m<3; m++)
   {
      for (int n=0; n<3; n++)
      {  
      COLORREF rgb=img_new.GetPixel(j+n,i+m);
         int p=MyGetRValue(rgb);
                  smx=smx+p*operx[m][n];
                  smy=smy+p*opery[m][n];
      }
   }
   float G=smx*smx+smy*smy;
   int GD=(int)sqrt(G);
           
   if(GD>100) // threshold to determine whether it is an edge
   {
         COLORREF cf = MyRGB(255,255,255);
         img_final.SetPixel(j+1,i+1,cf);
 
   }
  }
 }
  
   Invalidate(); //call the OnPaint to show the result

}