How to produce the effect of drawing a rectangle box surrounded the code, and put it in the figure? (Any methods including non-tikz-pgf method that helps is welcome)
An example of verbatimbox usage:
where codefrag.tex is
Alternately, if you wish to auto-number the code fragments, here I define the \numblock command, so that each code block is sequentially numbered. Once that is done, a code frag is placed as follows, quite simply:
Here is an example where \numblock is defined.
If I'm not mistaken, the question has been edited to emphasize the notion of putting the code listing into a "figure." The verbatimbox package can do it, because it's output is a box, which can easily be stuffed into a figure environment or, as I prefer, into the \bxfigure command of the boxhandler package.
In this case, the boxed code fragment constitutes the entire figure (minus the caption). However, that need not be the case. The second argument of \bxfigure can be tweaked to make \theverbbox part of a tabular environment, etc.