⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 toolbox.java

📁 j2me简单实例,j2me教程加源码,希望大家喜欢
💻 JAVA
字号:
package com.j2medev.chapter5;


import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import java.io.*;
import java.util.*;

/**
 * @name ToolBox
 * @brief class containing many helper methods
 * @author sunyuzhe   <sunyuzhe@hotmail.com>
 * @version 1.26
 */
public final class ToolBox implements MyGameInterface
{




        /**
         * paints outlined text using current color and black<br>
         * outline within specified position and anchor placement<br>
         * @name drawOutlinedText
         * @brief paints outlined  plain text
         * @version 1.2
         * @param g Graphics reference
         * @param a_Font font to be used
         * @param a_Msg string to be painted
         * @param x horizontal coords
         * @param y vertical coord
         * @param a_Align text alignment, set do default
         * @return none
         */
        public static final void drawOutlinedText( Graphics g, Font a_Font, String a_Msg, int x, int y, int a_Align )
        {
                /* prepare environment */
                int startx = x;
                int starty = y;
                int oldColor = g.getColor();
                Font oldFont = g.getFont();


                /* find start point - depends on align */
                if( (a_Align & Graphics.TOP) != 0 )
                        starty = y;
                if( (a_Align & Graphics.BOTTOM) != 0 )
                        starty = y - a_Font.getHeight();
                if( (a_Align & Graphics.VCENTER) != 0 )
                        starty = y - a_Font.getHeight()/2;
                if( (a_Align & Graphics.LEFT) != 0 )
                        startx = x;
                if( (a_Align & Graphics.RIGHT) != 0 )
                        startx = x - a_Font.stringWidth( a_Msg );
                if( (a_Align & Graphics.HCENTER) != 0 )
                        startx = x - a_Font.stringWidth( a_Msg )/2;

                /* static text */
                g.setFont( a_Font );
                g.setColor(0,0,0);
                g.drawString( a_Msg, startx-1, starty-1, Graphics.TOP|Graphics.LEFT);
                g.drawString( a_Msg, startx-1, starty+1, Graphics.TOP|Graphics.LEFT);
                g.drawString( a_Msg, startx+1, starty-1, Graphics.TOP|Graphics.LEFT);
                g.drawString( a_Msg, startx+1, starty+1, Graphics.TOP|Graphics.LEFT);
                g.setColor( oldColor ) ;
                g.drawString( a_Msg, startx,   starty,   Graphics.TOP|Graphics.LEFT);
                g.setFont( oldFont );
        }/// END FUNC

        /**
         * paints outlined text using current color and black<br>
         * outline within specified position and anchor placement<br>
         * Version without alignment setting - default used - horizontaly and verticaly centered<br>
         * @name drawOutlinedText
         * @brief paints outlined  plain text
         * @version 1.2
         * @param g Graphics reference
         * @param a_Font font to be used
         * @param a_Msg string to be painted
         * @param x horizontal coords
         * @param y vertical coord
         * @return none
         */
        public static final void drawOutlinedText( Graphics g, Font a_Font, String a_Msg, int x, int y )
        {
                /* paint the string */
                drawOutlinedText( g, a_Font, a_Msg, x, y, Graphics.HCENTER|Graphics.VCENTER );
        }/// END FUNC




        public static String readStream( Object a_Class, String a_Name,String encoding)
        {
          String str="";

          try
          {
           InputStream is=  a_Class.getClass().getResourceAsStream( a_Name );
            int enc;
            if ("UTF8".equals(encoding))
            {
            enc = 10;
            }
            else if ("UNICODE".equals(encoding))
            {
            enc = 20;
            }
            else if ("ANSI".equals(encoding))
            {
            enc = 30;
            }

            else
            {
            throw new UnsupportedEncodingException(encoding);
           }



            final int BLOCKSIZE = 4096;
            byte[] bb = new byte[BLOCKSIZE];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bos.write(0);
            bos.write(0);
            int len = is.read(bb);
            while (len > 0) {
              bos.write(bb, 0, len);
              len = is.read(bb);
            }
            bos.close();
            bb = bos.toByteArray();
            bb[0] = (byte) ( ( (bb.length - 2) & 0xff00) >> 8);
            bb[1] = (byte) (bb.length - 2);

            switch (enc) {
              case 30:  //ANSI
               str=new String(getResourceAsBytes(a_Class,a_Name)) ;
              case 10: // UTF8
                DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bb));
                str = dis.readUTF();
                dis.close();
                break;
              case 20: // Unicode
                StringBuffer buf = new StringBuffer();
                char first = (char) ( ( (bb[2] << 8) & 0xff00) | (bb[3] & 0xff));
                int i1 = 0, i2 = 1;
                switch (first) {
                  case '\uFEFF':
                    break;
                  case '\uFFFE':
                    i1 = 1;
                    i2 = 0;
                    break;
                  default:
                    buf.append(first);
                }
                for (int i = 4; i < bb.length; i += 2) {
                  buf.append( (char) ( ( (bb[i + i1] << 8) & 0xff00) |
                                      (bb[i + i2] & 0xff)));
                }
                str = buf.toString();
                System.out.println("str is "+str);
                break;
            }

            if ('\uFEFF' == str.charAt(0)) {
              str = str.substring(1);
            }
          }
          catch(Exception e)
          {
            System.out.println("e is "+e.toString());
          }
          return str;
        }


        /////////////////////////////////////////////////////////
        /// Text operations                                   ///
        /////////////////////////////////////////////////////////

        /**
         * splits text in pieces with line length no<br>
         * longer then given one as a_LineLength.<br>
         * The return argument is vector containing lines.<br>
         * the base text is to be taken from static jar<br>
         * archive resource referenced by a_Class and a_Name<br>
         * @name splitText
         * @brief splits text in lines
         * @version 1.0
         * @param a_Str string to be splitted
         * @param a_LineLength maximum text length
         * @param a_Font font to be used
         * @return none
         */
        public static final Vector splitText( Object a_Class, String a_Name, int a_LineLength, Font a_Font )
        {
                /* prepare environment */
                //byte[] bytes;
                String str;
                /* get bytes */
                try {
                //	bytes = getResourceAsBytes( a_Class, a_Name );
                       str= readStream( a_Class , a_Name ,"UNICODE");
                }// ~try
                catch( Exception e ) {
                        System.out.println( "[ERR] cannot load resource: " + a_Name );
                        return null;
                }// ~catch

                /* and return vector containing splitted text */
                //return splitText( new String(bytes), a_LineLength, a_Font );
                return splitText( str, a_LineLength, a_Font );
        }/// END FUNC splitText


        /**
         * splits text in pieces with line length no<br>
         * longer then given one as a_LineLength.<br>
         * The return argument is vector containing lines<br>
         * @name splitText
         * @brief splits text in lines
         * @version 1.2
         * @param a_Str string to be splitted
         * @param a_LineLength maximum text length
         * @param a_Font font to be used
         * @return none
         */
        public static Vector splitText( String a_Str, int a_LineLength, Font a_Font )
        {
                /* prepare environment */
                Vector m_Caption = new Vector();
                int lastSpace = 0;
                String tmpStr = "";
                char currentChar = '\0';

                /* perform text splittin */
                for(int i=0; i<a_Str.length(); i++)
                {
                        currentChar = a_Str.charAt(i);
                        if(currentChar=='\r' || currentChar=='\n')
                        {
                                m_Caption.addElement(tmpStr);
                                tmpStr = "";
                                lastSpace = -1;
                        }// ~if
                        else if(currentChar!='\n') {
                                tmpStr+=currentChar;
                                if(currentChar==' ') {
                                        lastSpace = tmpStr.length()-1;
                                }// ~else
                                if(a_Font.stringWidth(tmpStr)>a_LineLength) {
                                        if(currentChar==' ') {
                                                m_Caption.addElement(tmpStr.substring(0, tmpStr.length()-1)); //skip last space
                                                tmpStr = "";
                                        }// ~if
                                        else {
                                                if(lastSpace!=-1) {
                                                        m_Caption.addElement(tmpStr.substring(0, lastSpace+1));
                                                        tmpStr = tmpStr.substring(lastSpace+1);
                                                }// ~else
                                                else {
                                                        m_Caption.addElement(tmpStr.substring(0, tmpStr.length()-1));
                                                        tmpStr = ""+currentChar;
                                                }// ~else
                                        }// ~else
                                        lastSpace = -1;
                                }// ~if
                        }// ~else
                }// ~for
                if(tmpStr.length()>0)
                        m_Caption.addElement(tmpStr);
                return m_Caption;
        }/// END FUNC splitText

        /////////////////////////////////////////////////////////
        /// Hashtable utilities                               ///
        /////////////////////////////////////////////////////////




        /**
         * this routine allows to retreive data<br>
         * holded in jar archive<br>
         * @name getResourceAsBytes
         * @brief gets data from jar file
         * @version 1.0
         * @param a_Class class reference
         * @param a_Name resource name referenced from class
         * @return byte array containing resource data
         */
        public static final byte[] getResourceAsBytes( Object a_Class, String a_Name ) throws IOException
        {
                ByteArrayOutputStream bout;
                InputStream in = a_Class.getClass().getResourceAsStream( a_Name );
                bout = new ByteArrayOutputStream();
                for (int ret = in.read(); ret >= 0; ret = in.read())
                        bout.write(ret);
                return bout.toByteArray();
        }/// END FUNC getResourceAsBytes

}//// END CLASS ToolBox

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -