Counter in J2ME

Hi,
I need to add a counter to my MIDlet to count the number of times the MIDlet is launched. Could you please give me some hint to do it?
Thank you.
Message was edited by:
Potomoto

Hi,
Basically I want to add a counter so that if the MIDlet is start for the first time it will prompt user for new password, if not, it will prompt for the password user entered previously (during first time). Or is this the way to do it?
int counter = 0;
do{
display = Display.getDisplay (this);
pwForm = new Form("Enter New Password");
pw = new TextField("Password",null,6,TextField.NUMERIC pwForm.append(pw);
get_newPW = new Command("Done",Command.OK,1); pwForm.addCommand(get_newPW);
pwForm.setCommandListener(this);
counter++;
while(counter != 1);
display = Display.getDisplay (this);
userpwForm = new Form("Enter Password");
userpw = new TextField("Password",null,6,TextField.NUMERIC);
userpwForm.append(userpw);
compare_pw = new Command("Done",Command.OK,1);
userpwForm.addCommand(compare_pw);
userpwForm.setCommandListener(this);

Similar Messages

  • J2ME game timer

    Hi,
    I am developing a J2ME game. At the moment i have code which will terminate the game if the game is reaches the time set.
    Now i want to be able to display the count down on the actual game. I want to display it anywhere on the screen but im not sure what i really need to implement to physically the actual counter.
    Can anybody help.
    Thanks

    Problem solved. :)
    Comments are welcome. :)
        public void run()
            int millis_per_tick = 100;
            int counter = 1000/millis_per_tick;
            timeLeftInMillis = 180000;
            Thread currentThread = Thread.currentThread();
            try
                // This ends when myThread is set to null, or when
                // it is subsequently set to a new thread; either way, the
                // current thread should terminate.
                while (currentThread == myThread)
                    long startTime = System.currentTimeMillis();
                    repaint(0, 0, screenWidth, screenHeight);
                    serviceRepaints();
                    long timeTaken = System.currentTimeMillis() - startTime;
                    if (timeTaken < millis_per_tick)
                        synchronized (this)
                            wait(millis_per_tick - timeTaken);
                    if (counter == 0) {
                        timeLeftInMillis = timeLeftInMillis - 1000;
                        counter = 1000/millis_per_tick;
                    else
                        counter--;
                    if (timeLeftInMillis<0) {
                        synchronized(this){
                            isGameOver = true;
            catch (InterruptedException e)
        }

  • J2ME on cell phones questions

    Hi,
    I'm in the process of picking a project and wanted to see how doable it is. The project involves a cell phone and a Java program to use Bluetooth. This is real unknown territory for me so my questions are very simple. First does J2ME have packages/classes that allow for bluetooth communication (name)? Or is that a separate package I need to find?
    Second, can you save to files/permanent memory from an application running on a cell phone (to save some program settings etc). On the cheapest cell phone usually how little memroy is available? Also can you name some classes that allow for this in J2ME (other libraries).
    Finally how standard is all this? What's the probability that the program will run on all of the new cell phones? On all new cell phones from same manufacturer?
    Thanks.

    Hi,
    J2ME has JSR 82, that specifies BlueTooth stack. It's bundled with latest WTK releases (and netBeans 4.0 Mobility Pack as well). If it's available on device depends on HW equipment of the device of course.
    For your second Q: RMS storage is defined by MIDP 1.0 itself so yes, you can store some records. Not sure about the size I guess you can count on 8kb. The storage will be more , least I know of is 30kb on Nokia 6310, usual sizes are 1-5 Mb, smartphones use MMC cards, so the size can grow to hundreds of megs.
    Peter

  • How to Create trial version of my j2me application??

    Hey..
    could please anyone write a short note on safest way of creating a trial version of my j2me application?? like i want to limit the number of tries.. like say 25 tries..
    are there any applications that do this.. or could u suggest good coding methods.. ??
    thanks a lot!

    rakesh.pachava wrote:
    Hi,
    You can use the Record Store implementation to count the number of tries.
    But if once the app is uninstalled then the record store is also lost.
    If you want you can use the File Connection API to write to file system.
    This asks for user permissions.
    Regards,
    Rakesh pachawa.yes.. this is the method im using.. & i dont want to access the File System directly.. cause i want maximum compatibility. I don't mind re-installing the application causing the trial to be re-started.. thats fine.
    but i don't want someone to be able to crack the class files by taking out the code which checks the Record Store..
    how are j2me applications normally cracked pls??

  • Design Patterns, OO Design, and J2ME performance

    Hello- I am a J2ME newbie. I am a design patterny/OO kind of guy using J2SE. I'm trying to create a facade for the business logic on a project I'm working on which will work on both J2ME and J2SE. I have come up with an acceptable design, but I am afraid that the bytecode may end up being way too large for J2ME. For example, I used the command pattern for some functionality, which results in many small Command classes, which is nice for extensibility and functional encapsulation, but creates extra bytecode. Another example is I like to throw specific business exceptions, however, those also require a separate class for each exception. Another example is I like to use TypeSafe enumerations, again, new, unnecessary classes.
    I am aware of some workarounds (create a generic business exception, just put info into the message, don't use the command pattern, use bytes for non-typesafe constants), but I find myself resisting due to my hardcore OO/best practices tendencies. I guess J2ME is a whole different programming paradigm. How are you guys dealing with these issues? The most important issues with J2ME programming are small footprint and high performance, right? I guess I could write more procedural-ish code, but I am interested in any compromises that the OO guys here have come up with. Also, what size is an acceptable library/sdk in J2ME?
    thanks,
    Abraham

    I'm not an OO guy, but I can definitely say that you'll will have to find some comprmises in your designs (the generic business exeption is a very good example).
    Since you are making business apps, you do get some leeway on two issues:
    * As opposed to games, where every cycle counts, for a business app maintainability and scalability are you usually more important than performance, so OO techniques will often be a better choice than a slightly faster implementation.
    * You probably have more control over the devices you will be targetting. The most common limitation for MIDlet size these days is 64KB, so a library that more than 20-30KB probably won't be any good on these phones. But if you know your apps will be run on higher end phones you can make it a lot bigger, since they can often have MIDlets that are up to several MB in size.
    shmoove

  • How to know the image size and coding of our j2me project

    Hi,
    I have developed a game and i did the obfuscation. My jar size is now 170KB. How can differentiate the coding size and the image size from the total jar size.
    If i asked any thing wrongly, please forgive me and clarify my doubt.
    I am looking forward to meet ur queries if any.
    Thanks and Regards,
    Hithayath.

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- *** GENERATED FROM project.xml - DO NOT EDIT *** -->
    <project xmlns:projdeps2="http://www.netbeans.org/ns/ant-project-references/2" basedir=".." default="jar" name="-impl">
    <target name="pre-init"/>
    <target depends="pre-init" name="pre-load-properties">
    <property file="nbproject/private/private.properties"/>
    <property value="0.0.1" name="deployment.number"/>
    <property value="000002" name="deployment.counter"/>
    <property location="${netbeans.user}/build.properties" name="user.properties.file"/>
    <available file="${user.properties.file}" property="user.properties.file.exists"/>
    </target>
    <target unless="config.active" depends="pre-load-properties" name="exists.config.active">
    <echo message="Active configuration (config.active property) is not set - using default." level="warning"/>
    <property name="config.active" value=""/>
    </target>
    <target unless="netbeans.user" depends="pre-load-properties" name="exists.netbeans.user">
    <echo message="NetBeans IDE user directory (netbeans.user property) is not set. By specifying this property many properties required by the project will be automatically evaluated (e.g.: ant-ext library home, ...). You could also open this project in the NetBeans IDE - in this case this property would be set automatically." level="warning"/>
    </target>
    <target unless="user.properties.file.exists" depends="pre-load-properties" name="exists.user.properties.file">
    <echo message="User properties file (user.properties.file) property is not set. By specifying this property many properties required by the project will be automatically evaluated (e.g.: libraries, platforms, ...)." level="warning"/>
    </target>
    <target depends="pre-load-properties,exists.config.active,exists.netbeans.user,exists.user.properties.file" name="load-properties">
    <loadproperties srcfile="nbproject/project.properties">
    <filterchain>
    <containsregex replace="\1" pattern="^configs\.${config.active}\.(.*)"/>
    <concatfilter prepend="nbproject/project.properties"/>
    <containsregex pattern="^platform.active=|^deployment.method="/>
    </filterchain>
    </loadproperties>
    <loadproperties srcfile="${user.properties.file}">
    <filterchain>
    <replaceregex replace="platform." pattern="^platforms\.${platform.active}\."/>
    <replaceregex replace="deployment.scriptfile=" pattern="^deployment\.${deployment.method}\.scriptfile="/>
    </filterchain>
    </loadproperties>
    <loadproperties srcfile="nbproject/project.properties">
    <filterchain>
    <containsregex replace="\1" pattern="^configs\.${config.active}\.(.*)"/>
    <concatfilter prepend="nbproject/project.properties"/>
    </filterchain>
    </loadproperties>
    </target>
    <target unless="platform.active" depends="load-properties" name="exists.platform.active">
    <echo message="Active platform (platform.active property) in not set. If you set this and user.properties.file property, many properties required by the project will be automatically evaluated (e.g.: platform home, platform classpath, ...)." level="warning"/>
    </target>
    <target depends="load-properties" unless="platform.configuration" name="exists.platform.configuration">
    <echo message="Platform configuration (platform.configuration) is not set. Using default (CLDC-1.0) configuration." level="warning"/>
    <property value="CLDC-1.0" name="platform.configuration"/>
    </target>
    <target depends="load-properties" unless="platform.profile" name="exists.platform.profile">
    <echo message="Platform profile (platform.profile) is not set. Using default (MIDP-1.0) profile." level="warning"/>
    <property value="MIDP-1.0" name="platform.profile"/>
    </target>
    <target depends="pre-init,load-properties,exists.platform.active,exists.platform.configuration,exists.platform.profile" name="init">
    <fail unless="libs.j2me_ant_ext.classpath">Classpath to J2ME Ant extension library (libs.j2me_ant_ext.classpath property) is not set. For example: location of mobility/modules/org-netbeans-modules-kjava-antext.jar file in the IDE installation directory.</fail>
    <fail unless="platform.home">Platform home (platform.home property) is not set. Value of this property should be ${platform.active.description} emulator home directory location.</fail>
    <fail unless="platform.bootclasspath">Platform boot classpath (platform.bootclasspath property) is not set. Value of this property should be ${platform.active.description} emulator boot classpath containing all J2ME classes provided by emulator.</fail>
    <fail unless="src.dir">Must set src.dir</fail>
    <fail unless="build.dir">Must set build.dir</fail>
    <fail unless="build.classes.dir">Must set build.classes.dir</fail>
    <fail unless="preprocessed.dir">Must set preprocessed.dir</fail>
    <fail unless="preverify.classes.dir">Must set preverify.classes.dir</fail>
    <fail unless="obfuscated.classes.dir">Must set obfuscated.classes.dir</fail>
    <fail unless="dist.dir">Must set dist.dir</fail>
    <fail unless="dist.jar">Must set dist.jar</fail>
    <fail unless="dist.jad">Must set dist.jad</fail>
    <fail unless="obfuscator.srcjar">Must set obfuscator.srcjar</fail>
    <fail unless="obfuscator.destjar">Must set obfuscator.destjar</fail>
    <fail unless="dist.javadoc.dir">Must set dist.javadoc.dir</fail>
    <property value="" name="abilities"/>
    <property value="" name="obfuscator.classpath"/>
    <property value="" name="kjava.configuration"/>
    <property value="UEI-1.0" name="platform.type"/>
    <property value="" name="platform.device"/>
    <property value="0" name="obfuscation.level"/>
    <property value="false" name="sign.enabled"/>
    <property value="file://" name="dist.jad.url"/>
    <property value="1.3" name="javac.source"/>
    <property value="1.1" name="javac.target"/>
    <property value="${file.encoding}" name="javac.encoding"/>
    <condition property="no.deps">
    <istrue value="${no.dependencies}"/>
    </condition>
    <condition property="no.javadoc.preview">
    <isfalse value="${javadoc.preview}"/>
    </condition>
    <condition value="${filter.excludes},**/*Test.java,**/test,**/test/**" property="filter.excludes.evaluated">
    <istrue value="${filter.exclude.tests}"/>
    </condition>
    <property value="${filter.excludes}" name="filter.excludes.evaluated"/>
    <condition value="" property="evaluated.run.security.domain">
    <isfalse value="${run.use.security.domain}"/>
    </condition>
    <condition value="" property="deployment.do.override.jarurl">
    <istrue value="${deployment.override.jarurl}"/>
    </condition>
    <property value="${run.security.domain}" name="evaluated.run.security.domain"/>
    <taskdef resource="org/netbeans/modules/kjava/antext/defs.properties">
    <classpath>
    <pathelement path="${libs.j2me_ant_ext.classpath}"/>
    </classpath>
    </taskdef>
    <uptodate targetfile="${preprocessed.dir}/.timestamp" property="no.clean.before.build">
    <srcfiles dir="nbproject">
    <include name="project.properties"/>
    <include name="build-impl.xml"/>
    </srcfiles>
    </uptodate>
    <condition property="skip.deployment">
    <equals trim="true" casesensitive="false" arg2="NONE" arg1="${deployment.method}"/>
    </condition>
    <condition property="skip-sign-keystore-password-input">
    <or>
    <isfalse value="${sign.enabled}"/>
    <and>
    <isset property="sign.keystore"/>
    <isset property="sign.keystore.password"/>
    <not>
    <equals trim="true" arg2="" arg1="${sign.keystore}"/>
    </not>
    <not>
    <equals trim="true" arg2="" arg1="${sign.keystore.password}"/>
    </not>
    </and>
    </or>
    </condition>
    <condition property="skip-sign-alias-password-input">
    <or>
    <isfalse value="${sign.enabled}"/>
    <and>
    <isset property="sign.keystore"/>
    <isset property="sign.alias"/>
    <isset property="sign.alias.password"/>
    <not>
    <equals trim="true" arg2="" arg1="${sign.keystore}"/>
    </not>
    <not>
    <equals trim="true" arg2="" arg1="${sign.alias}"/>
    </not>
    <not>
    <equals trim="true" arg2="" arg1="${sign.alias.password}"/>
    </not>
    </and>
    </or>
    </condition>
    <antcall inheritrefs="true" inheritall="true" target="post-init"/>
    </target>
    <target name="post-init"/>
    <target name="deps-jar" depends="init" unless="no.deps"/>
    <target description="Clean project in case its meta information has changed." unless="no.clean.before.build" depends="init" name="conditional-clean">
    <antcall target="do-clean" inheritall="true" inheritrefs="true"/>
    </target>
    <target name="pre-preprocess"/>
    <target description="Preprocess project sources." depends="init,pre-preprocess,deps-jar,conditional-clean" name="preprocess">
    <mkdir dir="${preprocessed.dir}"/>
    <echo file="${preprocessed.dir}/.timestamp" message="ignore me"/>
    <nb-prep encoding="${javac.encoding}" preprocessfor="${config.active},${abilities}" destdir="${preprocessed.dir}">
    <fileset excludes="${filter.excludes.evaluated}" defaultexcludes="${filter.use.standard}" dir="${src.dir}"/>
    </nb-prep>
    <antcall inheritrefs="true" inheritall="true" target="post-preprocess"/>
    </target>
    <target name="post-preprocess"/>
    <target description="Extracts all bundled libraries." depends="init,deps-jar,conditional-clean" name="extract-libs">
    <mkdir dir="${build.classes.dir}"/>
    <nb-extract excludeManifest="true" dir="${build.classes.dir}">
    <classpath>
    <path path="${libs.classpath}"/>
    </classpath>
    </nb-extract>
    </target>
    <target name="pre-compile"/>
    <target description="Compile project classes." depends="init,preprocess,extract-libs,pre-compile" name="compile">
    <mkdir dir="${build.classes.dir}"/>
    <javac encoding="${javac.encoding}" bootclasspath="${platform.bootclasspath}" srcdir="${preprocessed.dir}" destdir="${build.classes.dir}" debug="${javac.debug}" optimize="${javac.optimize}" deprecation="${javac.deprecation}" target="${javac.target}" source="${javac.source}" includeantruntime="false">
    <classpath>
    <path path="${libs.classpath}"/>
    </classpath>
    </javac>
    <copy todir="${build.classes.dir}">
    <fileset excludes="${filter.excludes.evaluated},${build.classes.excludes}" defaultexcludes="${filter.use.standard}" dir="${src.dir}"/>
    </copy>
    <antcall inheritrefs="true" inheritall="true" target="post-compile"/>
    </target>
    <target name="post-compile"/>
    <target name="pre-compile-single"/>
    <target description="Compile selected project classes." depends="init,preprocess,extract-libs,pre-compile-single" name="compile-single">
    <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail>
    <mkdir dir="${build.classes.dir}"/>
    <javac encoding="${javac.encoding}" includes="${javac.includes}" bootclasspath="${platform.bootclasspath}" destdir="${build.classes.dir}" srcdir="${preprocessed.dir}" debug="${javac.debug}" optimize="${javac.optimize}" deprecation="${javac.deprecation}" target="${javac.target}" source="${javac.source}" includeantruntime="false">
    <classpath>
    <path path="${libs.classpath}"/>
    </classpath>
    </javac>
    <antcall inheritrefs="true" inheritall="true" target="post-compile-single"/>
    </target>
    <target name="post-compile-single"/>
    <target depends="init" name="create-jad">
    <mkdir dir="${build.dir}"/>
    <dirname property="dist.jad.dir" file="${dist.dir}/${dist.jad}"/>
    <mkdir dir="${dist.jad.dir}"/>
    <condition value="${manifest.apipermissions}" property="evaluated.manifest.apipermissions">
    <not>
    <equals arg2="MIDP-1.0" arg1="${platform.profile}"/>
    </not>
    </condition>
    <condition value="${manifest.pushregistry}" property="evaluated.manifest.pushregistry">
    <not>
    <equals arg2="MIDP-1.0" arg1="${platform.profile}"/>
    </not>
    </condition>
    <condition property="contains.manifest.configuration">
    <contains string="${manifest.others}" substring="MicroEdition-Configuration: "/>
    </condition>
    <condition property="contains.manifest.profile">
    <contains string="${manifest.others}" substring="MicroEdition-Profile: "/>
    </condition>
    <property name="evaluated.manifest.apipermissions" value=""/>
    <property name="evaluated.manifest.pushregistry" value=""/>
    <property value="" name="manifest.jad"/>
    <property value="" name="manifest.manifest"/>
    <echo file="${dist.dir}/${dist.jad}">${manifest.midlets}${evaluated.manifest.apipermissions}${evaluated.manifest.pushregistry}${manifest.others}${manifest.jad}</echo>
    <echo file="${build.dir}/manifest.mf">${manifest.midlets}${evaluated.manifest.apipermissions}${evaluated.manifest.pushregistry}${manifest.others}${manifest.manifest}</echo>
    <antcall inheritrefs="true" inheritall="true" target="add-configuration"/>
    <antcall inheritrefs="true" inheritall="true" target="add-profile"/>
    </target>
    <target unless="contains.manifest.configuration" name="add-configuration">
    <echo append="true" file="${dist.dir}/${dist.jad}">MicroEdition-Configuration: ${platform.configuration}
    </echo>
    <echo append="true" file="${build.dir}/manifest.mf">MicroEdition-Configuration: ${platform.configuration}
    </echo>
    </target>
    <target unless="contains.manifest.profile" name="add-profile">
    <echo append="true" file="${dist.dir}/${dist.jad}">MicroEdition-Profile: ${platform.profile}
    </echo>
    <echo append="true" file="${build.dir}/manifest.mf">MicroEdition-Profile: ${platform.profile}
    </echo>
    </target>
    <target name="pre-obfuscate"/>
    <target description="Up-to-date check before obfuscation." depends="init,compile" name="obfuscate-check">
    <uptodate targetfile="${obfuscator.destjar}" property="no.obfusc">
    <srcfiles dir="${build.classes.dir}"/>
    </uptodate>
    </target>
    <target unless="no.obfusc" description="Obfuscate project classes." depends="init,compile,obfuscate-check,pre-obfuscate" name="obfuscate">
    <dirname property="obfuscator.srcjar.dir" file="${obfuscator.srcjar}"/>
    <dirname property="obfuscator.destjar.dir" file="${obfuscator.destjar}"/>
    <mkdir dir="${obfuscator.srcjar.dir}"/>
    <mkdir dir="${obfuscator.destjar.dir}"/>
    <jar basedir="${build.classes.dir}" jarfile="${obfuscator.srcjar}"/>
    <property value="" name="obfuscation.custom"/>
    <nb-obfuscate extraScript="${obfuscation.custom}" obfuscationLevel="${obfuscation.level}" classpath="${platform.bootclasspath}" obfuscatorclasspath="${obfuscator.classpath}" destjar="${obfuscator.destjar}" srcjar="${obfuscator.srcjar}"/>
    <mkdir dir="${obfuscated.classes.dir}"/>
    <unjar dest="${obfuscated.classes.dir}" src="${obfuscator.destjar}"/>
    <antcall inheritrefs="true" inheritall="true" target="post-obfuscate"/>
    </target>
    <target name="post-obfuscate"/>
    <target name="pre-preverify"/>
    <target description="Preverify project classes." depends="init,compile,obfuscate,pre-preverify" name="preverify">
    <mkdir dir="${preverify.classes.dir}"/>
    <nb-preverify commandline="${platform.preverifycommandline}" platformtype="${platform.type}" platformhome="${platform.home}" configuration="${platform.configuration}" classpath="${platform.bootclasspath}" destdir="${preverify.classes.dir}" srcdir="${obfuscated.classes.dir}"/>
    <antcall inheritrefs="true" inheritall="true" target="post-preverify"/>
    </target>
    <target name="post-preverify"/>
    <target unless="skip-sign-keystore-password-input" if="netbeans.home" depends="init" name="set-keystore-password">
    <nb-enter-password passwordproperty="sign.keystore.password" keystore="${sign.keystore}"/>
    </target>
    <target unless="skip-sign-alias-password-input" if="netbeans.home" depends="init" name="set-alias-password">
    <nb-enter-password passwordproperty="sign.alias.password" keyalias="${sign.alias}" keystore="${sign.keystore}"/>
    </target>
    <target name="pre-jar"/>
    <target description="Build jar and application descriptor." depends="init,preverify,create-jad,set-keystore-password,set-alias-password,pre-jar" name="jar">
    <dirname property="dist.jar.dir" file="${dist.dir}/${dist.jar}"/>
    <mkdir dir="${dist.jar.dir}"/>
    <jar manifest="${build.dir}/manifest.mf" jarfile="${dist.dir}/${dist.jar}" compress="${jar.compress}">
    <fileset dir="${preverify.classes.dir}"/>
    <fileset dir="${obfuscated.classes.dir}">
    <exclude name="**/*.class"/>
    </fileset>
    </jar>
    <nb-jad aliaspassword="${sign.alias.password}" alias="${sign.alias}" keystorepassword="${sign.keystore.password}" keystore="${sign.keystore}" sign="${sign.enabled}" url="${dist.jar}" jarfile="${dist.dir}/${dist.jar}" jadfile="${dist.dir}/${dist.jad}"/>
    <antcall inheritrefs="true" inheritall="true" target="post-jar"/>
    </target>
    <target name="post-jar"/>
    <target description="Rebuild the application." depends="init,clean,jar" name="rebuild"/>
    <target description="Run MIDlet suite." depends="init,jar" name="run">
    <nb-run commandline="${platform.runcommandline}" securitydomain="${evaluated.run.security.domain}" execmethod="${run.method}" platformtype="${platform.type}" platformhome="${platform.home}" device="${platform.device}" jadurl="${dist.jad.url}" jadfile="${dist.dir}/${dist.jad}"/>
    </target>
    <target description="Quick Run already built MIDlet suite." depends="init" name="run-no-build">
    <nb-run commandline="${platform.runcommandline}" securitydomain="${evaluated.run.security.domain}" execmethod="${run.method}" platformtype="${platform.type}" platformhome="${platform.home}" device="${platform.device}" jadurl="${dist.jad.url}" jadfile="${dist.dir}/${dist.jad}"/>
    </target>
    <target depends="init,clean,jar" description="Debug project." name="debug">
    <delete file="${preprocessed.dir}/.timestamp"/>
    <parallel>
    <nb-run commandline="${platform.debugcommandline}" securitydomain="${evaluated.run.security.domain}" execmethod="${run.method}" jadfile="${dist.dir}/${dist.jad}" device="${platform.device}" platformhome="${platform.home}" platformtype="${platform.type}" debuggeraddressproperty="jpda.port" debugserver="true" debugsuspend="true" debug="true"/>
    <sequential>
    <sleep seconds="5"/>
    <antcall target="nbdebug"/>
    </sequential>
    </parallel>
    </target>
    <target if="netbeans.home" description="Start NetBeans debugger" name="nbdebug">
    <nb-kjava-debug period="2000" timeout="30000" name="${app.codename}" address="${jpda.port}">
    <bootclasspath>
    <path path="${platform.bootclasspath}"/>
    </bootclasspath>
    <classpath>
    <path path="${dist.dir}/${dist.jar}"/>
    </classpath>
    <sourcepath>
    <path path="${src.dir}"/>
    <path path="${libs.src.path}"/>
    </sourcepath>
    </nb-kjava-debug>
    </target>
    <target depends="init,preprocess" name="javadoc">
    <mkdir dir="${dist.javadoc.dir}"/>
    <javadoc private="${javadoc.private}" windowtitle="${javadoc.windowtitle}" version="${javadoc.version}" author="${javadoc.author}" splitindex="${javadoc.splitindex}" noindex="${javadoc.noindex}" nonavbar="${javadoc.nonavbar}" use="${javadoc.use}" notree="${javadoc.notree}" bootclasspath="${platform.bootclasspath}" destdir="${dist.javadoc.dir}" source="${javac.source}">
    <classpath>
    <path path="${libs.classpath}"/>
    </classpath>
    <sourcepath>
    <pathelement location="${preprocessed.dir}"/>
    </sourcepath>
    <fileset dir="${preprocessed.dir}"/>
    </javadoc>
    <antcall target="browse-javadoc"/>
    </target>
    <target unless="no.javadoc.preview" if="netbeans.home" name="browse-javadoc">
    <nbbrowse file="${dist.javadoc.dir}/index.html"/>
    </target>
    <target name="pre-clean"/>
    <target description="Clean build products." if="no.clean.before.build" depends="init,conditional-clean" name="clean">
    <antcall inheritrefs="true" inheritall="true" target="do-clean"/>
    </target>
    <target depends="pre-clean" name="do-clean">
    <delete dir="${preprocessed.dir}"/>
    <delete dir="${build.classes.dir}"/>
    <delete file="${obfuscator.srcjar}"/>
    <delete file="${obfuscator.destjar}"/>
    <delete dir="${obfuscated.classes.dir}"/>
    <delete dir="${preverify.classes.dir}"/>
    <delete file="${build.dir}/manifest.mf"/>
    <delete file="${dist.dir}/${dist.jar}"/>
    <delete file="${dist.dir}/${dist.jad}"/>
    <delete dir="${dist.javadoc.dir}"/>
    <antcall inheritrefs="true" inheritall="true" target="post-clean"/>
    </target>
    <target name="post-clean"/>
    <target name="pre-deploy"/>
    <target if="deployment.do.override.jarurl" depends="init,jar,pre-deploy" name="override-jad">
    <property value="${dist.jar}" name="deployment.jarurl"/>
    <nb-jad aliaspassword="${sign.alias.password}" alias="${sign.alias}" keystorepassword="${sign.keystore.password}" keystore="${sign.keystore}" sign="${sign.enabled}" url="${deployment.jarurl}" jarfile="${dist.dir}/${dist.jar}" jadfile="${dist.dir}/${dist.jad}"/>
    </target>
    <target unless="skip.deployment" if="deployment.method" depends="init,jar,override-jad,pre-deploy" name="deploy">
    <fail unless="deployment.scriptfile">Property deployment.${deployment.method}.scriptfile not set. The property should point to an Ant script providing ${deployment.method} deployment.</fail>
    <ant inheritrefs="true" inheritall="true" antfile="${deployment.scriptfile}">
    <property location="${dist.dir}/${dist.jad}" name="deployment.jad"/>
    <property location="${dist.dir}/${dist.jar}" name="deployment.jar"/>
    </ant>
    <propertyfile file="nbproject/private/private.properties">
    <entry pattern="000000" default="2" operation="+" type="int" key="deployment.counter"/>
    <entry value="${deployment.counter}" key="deployment.number"/>
    </propertyfile>
    <replaceregexp replace="deployment.number=\2\3.\5\6.\8\9" match="^deployment.number=[0-9]*(0|([1-9]))([0-9])(0|([1-9]))([0-9])(0|([1-9]))([0-9])$" file="nbproject/private/private.properties" byline="true"/>
    <antcall inheritrefs="true" inheritall="true" target="post-deploy"/>
    </target>
    <target name="post-deploy"/>
    <target name="for-all-configs">
    <antcall inheritrefs="false" inheritall="false" target="${target.to.call}">
    <param value="" name="config.active"/>
    </antcall>
    </target>
    <target name="jar-all">
    <antcall target="for-all-configs">
    <param value="jar" name="target.to.call"/>
    </antcall>
    </target>
    <target name="javadoc-all">
    <antcall target="for-all-configs">
    <param value="javadoc" name="target.to.call"/>
    </antcall>
    </target>
    <target name="deploy-all">
    <antcall target="for-all-configs">
    <param value="deploy" name="target.to.call"/>
    </antcall>
    </target>
    <target name="rebuild-all">
    <antcall target="for-all-configs">
    <param value="rebuild" name="target.to.call"/>
    </antcall>
    </target>
    <target depends="load-properties" name="clean-all">
    <fail unless="build.root.dir">Property build.root.dir is not set. By default its value should be \"build\".</fail>
    <fail unless="dist.root.dir">Property dist.root.dir is not set. By default its value should be \"dist\".</fail>
    <delete dir="${build.root.dir}"/>
    <delete dir="${dist.root.dir}"/>
    <antcall target="for-all-configs">
    <param value="clean" name="target.to.call"/>
    </antcall>
    </target>
    </project>
    I have pasted the content of that file, please do the needs....

  • J2ME Countdown Timer

    I'm working on a J2ME game that requires the use of a countdown timer. I've put in a Timer.scheduleAtFixedRate call inside my run() method, but apparently it's taking up a lot of resources and it's proceeding too fast (a 3-minute countdown will finish in about 30 seconds or less).
    I have a separate method that calculates the amount of time left in terms of minutes and seconds, and the output will jump irregularly (say from 2:59 to 1:13 to 0:57, and so on).
    Here's the piece of code in question:
        public void run() {
            Thread currentThread = Thread.currentThread();
            //timeLeftInMillis is an int
            timeLeftInMillis = 180000;
            try
                // This ends when myThread is set to null, or when
                // it is subsequently set to a new thread; either way, the
                // current thread should terminate.
                while (currentThread == myThread)
                    //myTimer is a Timer object instantiated in the
                    //constructor
                    myTimer.scheduleAtFixedRate(new TimerTask () {
                        public void run(){
                            GameScreen.timeLeftInMillis=GameScreen.timeLeftInMillis-1000;
                            System.out.println(GameScreen.timeLeftInMillis);
                            if (GameScreen.timeLeftInMillis<= 0) {
                                    synchronized (this) {
                                        GameScreen.isGameOver = true;
                                        this.cancel();
                    }, 0, 1000L);
                    repaint(0, 0, screenWidth, screenHeight);
                    serviceRepaints();
            catch (Exception e)
        }Can anyone help me figure out what's wrong with this timer? Any help at all would be appreciated.
    Thanks. :)

    Problem solved. :)
    Comments are welcome. :)
        public void run()
            int millis_per_tick = 100;
            int counter = 1000/millis_per_tick;
            timeLeftInMillis = 180000;
            Thread currentThread = Thread.currentThread();
            try
                // This ends when myThread is set to null, or when
                // it is subsequently set to a new thread; either way, the
                // current thread should terminate.
                while (currentThread == myThread)
                    long startTime = System.currentTimeMillis();
                    repaint(0, 0, screenWidth, screenHeight);
                    serviceRepaints();
                    long timeTaken = System.currentTimeMillis() - startTime;
                    if (timeTaken < millis_per_tick)
                        synchronized (this)
                            wait(millis_per_tick - timeTaken);
                    if (counter == 0) {
                        timeLeftInMillis = timeLeftInMillis - 1000;
                        counter = 1000/millis_per_tick;
                    else
                        counter--;
                    if (timeLeftInMillis<0) {
                        synchronized(this){
                            isGameOver = true;
            catch (InterruptedException e)
        }

  • J2me on ppc phones?

    hey, I was wondering if its possible to put java stuff on pda phones like imate jasjar and stuff. the only programming language i know is java, and that's y i want to make one 4 my phone. also, i tried microsoft visual studio, but that requires learning c#, c++, or visual basic, and i want to try to stick to java. also, is it possible to add in funtions as in touchscreen, and pda keyboard stuff? just wondering. cuz my thing doesn't have normal phone buttons, just a keyboard.

    Hi,
    J2ME has JSR 82, that specifies BlueTooth stack. It's bundled with latest WTK releases (and netBeans 4.0 Mobility Pack as well). If it's available on device depends on HW equipment of the device of course.
    For your second Q: RMS storage is defined by MIDP 1.0 itself so yes, you can store some records. Not sure about the size I guess you can count on 8kb. The storage will be more , least I know of is 30kb on Nokia 6310, usual sizes are 1-5 Mb, smartphones use MMC cards, so the size can grow to hundreds of megs.
    Peter

  • Is there any alternative for FileConnection in j2me

    hi,
    i want to read and write images from phone memory.i use the Fileconnection for that the pbm for using FileConnection v need the support of JSR-75 in mobile.only few mobiles have the support of JSR-75.Is there any possible way to read and write images from phonememory other than FileConnection and also theRMS .
    thanx a lot

    Hi im write this code to open the image file and show that in canvas :
    as a class
    FileBrowser.java as a example on wtk 2.2 with modification
    import java.util.*;
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.io.file.*;
    import javax.microedition.lcdui.*;
    * Demonstration MIDlet for File Connection API. midlet MIDlet implements simple
    * file browser for the filesystem avaliable to the J2ME applications.
    class FileBrowser implements CommandListener {
        private String currDirName;
        private Command view = new Command("View", Command.ITEM, 1);
        private Command creat = new Command("New", Command.ITEM, 2);
        private Command creatOK = new Command("Oke", Command.OK, 1);
        private Command prop = new Command("Properti", Command.ITEM, 2);
        private Command back = new Command("Kembali", Command.BACK, 2);
        private Command exit = new Command("Batal", Command.EXIT, 3);
        private Command cmOpenCrop = new Command("Open File To Crop", Command.ITEM, 1);
        private TextField   nameInput;  // Input field for new file name
        private ChoiceGroup typeInput;  // Input fiels for file type (regular/dir)
        private Midlet midlet;
        private final static String[] attrList = { "Baca", "Tulis", "Sembunyikan" };
        private final static String[] typeList = { "File Biasa", "Direktori" };
        private final static String[] monthList = { "Jan", "Feb", "Mar", "Apr",
        "May", "Jun", "Jul", "Aug",
        "Sep", "Oct", "Nov", "Dec" };
        private Image dirIcon, fileIcon, photoIcon;
        private Image[] iconList;
        /* special string denotes upper directory */
        private final static String UP_DIRECTORY = "..";
        /* special string that denotes apper directory accessible by midlet browser.
         * midlet virtual directory contains all roots.
        private final static String MEGA_ROOT = "/";
        /* separator string as defined by FC specification */
        private final static String SEP_STR = "/";
        /* separator character as defined by FC specification */
        private final static char   SEP = '/';
        public FileBrowser(Midlet midlet) {
            this.midlet = midlet;
            currDirName = MEGA_ROOT;
            try {
                dirIcon = Image.createImage("/icons/dir.png");
            } catch (IOException e) {
                dirIcon = null;
            try {
                photoIcon = Image.createImage("/icons/photo.png");
            } catch (IOException e) {
                photoIcon = null;
            try {
                fileIcon = Image.createImage("/icons/file.png");
            } catch (IOException e) {
                fileIcon = null;
            iconList = new Image[] { fileIcon, dirIcon};
            new Thread(new Runnable() {
             public void run(){
               RunAplikasi(); }
            }).start();
        public void RunAplikasi() {
            try {
                showCurrDir();
            } catch (SecurityException e) {
                Alert alert = new Alert("Error",
                    "You are not authorized to access the restricted API",
                    null, AlertType.ERROR);
                alert.setTimeout(Alert.FOREVER);
                Form form = new Form("Cannot access FileConnection");
                form.append(new StringItem(null,
                    "You cannot run midlet MIDlet with the current permissions. "
                    + "Sign the MIDlet suite, or run it in a different security domain"));
                form.addCommand(exit);
                form.setCommandListener(this);
                Display.getDisplay(midlet).setCurrent(alert, form);
            } catch (Exception e) {
                e.printStackTrace();
        public void commandAction(Command c, Displayable d) {
            if (c == view) {
                List curr = (List)d;
                final String currFile = curr.getString(curr.getSelectedIndex());
                new Thread(new Runnable() {
                    public void run() {
                        if (currFile.endsWith(SEP_STR) || currFile.equals(UP_DIRECTORY)) {
                            traverseDirectory(currFile);
                        } else {
                            // Show file contents
                            showFile(currFile);
                }).start();
            } else if (c == prop) {
                List curr = (List)d;
                String currFile = curr.getString(curr.getSelectedIndex());
                showProperties(currFile);
            } else /*if (c == creat) {
                 //createFile();
            } else if (c == creatOK) {
                String newName = nameInput.getString();
                if (newName == null || newName.equals("")) {
                    Alert alert = new Alert("Error!",
                    "File Name is empty. Please provide file name",
                    null,
                    AlertType.ERROR);
                    alert.setTimeout(Alert.FOREVER);
                    Display.getDisplay(midlet).setCurrent(alert);
                } else {
                    // Create file in a separate thread and disable all commands
                    // except for "exit"
                    executeCreateFile(newName, typeInput.getSelectedIndex() != 0);
                    Display.getDisplay(midlet).getCurrent().removeCommand(creatOK);
                    Display.getDisplay(midlet).getCurrent().removeCommand(back);
            } else*/ if (c == back) {
                showCurrDir();
            } else if (c == exit) {
               midlet.SelesaiAplikasi();
            } else if (c == cmOpenCrop) {
               List curr = (List)d;
               String currFile = curr.getString(curr.getSelectedIndex());
               midlet.SelesaiOpen("file:///"+ currDirName + currFile,0,0);
        //Starts creatFile with another Thread
        private void executeCreateFile(final String name, final boolean val) {
            new Thread(new Runnable(){
                public void run(){
                    createFile(name, val);
            }).start();
         * Show file list in the current directory .
        void showCurrDir() {
            Enumeration e;
            int Panjang,Count,AdaEkstensi,IndexConcat = 0;
            String SimpanEkstensi,SaveTemp;
            char str[] = new char[10];
            Boolean Ketemu = new Boolean(false);
            FileConnection currDir = null;
            List browser;
            try {
                if (MEGA_ROOT.equals(currDirName)) {
                    e = FileSystemRegistry.listRoots();
                     browser = new List(currDirName, List.IMPLICIT);
                } else {
                    currDir = (FileConnection)Connector.open("file://localhost/" +
                                currDirName);
                    e = currDir.list();
                     browser = new List(currDirName, List.IMPLICIT);
                      // not root - draw UP_DIRECTORY
                     browser.append(UP_DIRECTORY, dirIcon);
                     browser.setSelectCommand(view);
                while (e.hasMoreElements()) {
                    String fileName = (String)e.nextElement();
                    if (fileName.charAt(fileName.length()-1) == SEP) {
                        // midlet is directory
                        browser.append(fileName, dirIcon);
                        browser.setSelectCommand(view);
                    } else {
                        // midlet is regular file
                        //cari tahu si ekstensi jika ada
                        Panjang = fileName.length();                
                        Count = 0;
                        AdaEkstensi = 0;
                        while (Count < Panjang && AdaEkstensi == 0)
                          if (fileName.charAt(Count) == '.')
                            AdaEkstensi = 1;
                            IndexConcat = Count+1;
                          Count++;
                        if (AdaEkstensi == 1)
                          //cari tahu apakah si ekstensi gambar atau bukan
                          SimpanEkstensi = new String("");
                          //SimpanEkstensi.concat(fileName.substring(IndexConcat,Panjang));
                          fileName.getChars(IndexConcat,Panjang,str,0);
                          if (str[0] == 'p' && str[1] == 'n' && str[2] == 'g'){
                             browser.append(fileName, photoIcon);
                             browser.addCommand(cmOpenCrop);
                             browser.setSelectCommand(view);
                          } else
                          if (str[0] == 'j' && str[1] == 'p' && str[2] == 'g'){
                             browser.append(fileName, photoIcon);
                             browser.addCommand(cmOpenCrop);
                             browser.setSelectCommand(view);
                          } else {
                             browser.append(fileName, fileIcon);
                             browser.setSelectCommand(view);
                        } else
                          browser.append(fileName, fileIcon);
                          browser.setSelectCommand(view);
                browser.addCommand(prop);
                //Do not allow creating files/directories beside root
                if (!MEGA_ROOT.equals(currDirName)) {
                    //browser.addCommand(creat);
                browser.addCommand(exit);
                browser.setCommandListener(this);
                if (currDir != null) {
                    currDir.close();
                Display.getDisplay(midlet).setCurrent(browser);
            } catch (IOException ioe) {
                ioe.printStackTrace();
        void traverseDirectory(String fileName) {
        /* In case of directory just change the current directory
         * and show it
            if (currDirName.equals(MEGA_ROOT)) {
                if (fileName.equals(UP_DIRECTORY)) {
                    // can not go up from MEGA_ROOT
                    return;
                currDirName = fileName;
            } else if (fileName.equals(UP_DIRECTORY)) {
                // Go up one directory
                // TODO use setFileConnection when implemented
                int i = currDirName.lastIndexOf(SEP, currDirName.length()-2);
                if (i != -1) {
                    currDirName = currDirName.substring(0, i+1);
                } else {
                    currDirName = MEGA_ROOT;
            } else {
                currDirName = currDirName + fileName;
            showCurrDir();
        void showFile(String fileName) {
            try {
                FileConnection fc = (FileConnection)
                    Connector.open("file://localhost/" + currDirName + fileName);
                if (!fc.exists()) {
                    throw new IOException("File does not exists");
                InputStream fis = fc.openInputStream();
                byte[] b = new byte[1024];
                int length = fis.read(b, 0, 1024);
                fis.close();
                fc.close();
                TextBox viewer = new TextBox("View File: " + fileName, null, 1024,
                TextField.ANY | TextField.UNEDITABLE);
                viewer.addCommand(back);
                viewer.addCommand(exit);
                viewer.setCommandListener(this);
                if (length > 0) {
                    viewer.setString(new String(b, 0, length));
                Display.getDisplay(midlet).setCurrent(viewer);
            } catch (Exception e) {
                Alert alert = new Alert("Error!",
                "Can not access file " + fileName
                + " in directory " + currDirName
                + "\nException: " + e.getMessage(),
                null,
                AlertType.ERROR);
                alert.setTimeout(Alert.FOREVER);
                Display.getDisplay(midlet).setCurrent(alert);
        void showProperties(String fileName) {
            try {
                if (fileName.equals(UP_DIRECTORY)) {
                    return;
                FileConnection fc = (FileConnection)Connector.open("file://localhost/"
                                    + currDirName + fileName);
                if (!fc.exists()) {
                    throw new IOException("File does not exists");
                Form props = new Form("Properties: " + fileName);
                ChoiceGroup attrs = new ChoiceGroup("Attributes:", Choice.MULTIPLE,
                attrList, null);
                attrs.setSelectedFlags(new boolean[] {fc.canRead(),
                fc.canWrite(),
                fc.isHidden()});
                props.append(new StringItem("Location:", currDirName));
                props.append(new StringItem("Type: ", fc.isDirectory() ?
                "Directory": "Regular File"));
                props.append(new StringItem("Modified:",myDate(fc.lastModified())));       
                props.append(attrs);
                props.addCommand(back);
                props.addCommand(exit);
                props.setCommandListener(this);
                fc.close();
                Display.getDisplay(midlet).setCurrent(props);
            } catch (Exception e) {
                Alert alert = new Alert("Error!",
                "Can not access file " + fileName
                + " in directory " + currDirName
                + "\nException: " + e.getMessage(),
                null,
                AlertType.ERROR);
                alert.setTimeout(Alert.FOREVER);
                Display.getDisplay(midlet).setCurrent(alert);
        void createFile() {
            Form creator = new Form("New File");
            nameInput = new TextField("Enter Name", null, 256, TextField.ANY);
            typeInput = new ChoiceGroup("Enter File Type", Choice.EXCLUSIVE,
            typeList, iconList);
            creator.append(nameInput);
            creator.append(typeInput);
            //creator.addCommand(creatOK);
            creator.addCommand(back);
            creator.addCommand(exit);
            creator.setCommandListener(this);
            Display.getDisplay(midlet).setCurrent(creator);
        void createFile(String newName, boolean isDirectory) {
            try {
                FileConnection fc = (FileConnection) Connector.open("file:///" +
                currDirName +
                newName);
                if (isDirectory) {
                    fc.mkdir();
                } else {
                    fc.create();
                showCurrDir();
            } catch (Exception e) {
                String s = "Can not create file '" + newName + "'";
                if (e.getMessage() != null && e.getMessage().length() > 0) {
                    s += "\n" + e;
                Alert alert = new Alert("Error!", s, null, AlertType.ERROR);        
                alert.setTimeout(Alert.FOREVER);
                Display.getDisplay(midlet).setCurrent(alert);
                // Restore the commands that were removed in commandAction()
                Display.getDisplay(midlet).getCurrent().addCommand(creatOK);
                Display.getDisplay(midlet).getCurrent().addCommand(back);
        private String myDate(long time) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date(time));
            StringBuffer sb = new StringBuffer();
            sb.append(cal.get(Calendar.HOUR_OF_DAY));
            sb.append(':');
            sb.append(cal.get(Calendar.MINUTE));
            sb.append(':');
            sb.append(cal.get(Calendar.SECOND));
            sb.append(',');
            sb.append(' ');
            sb.append(cal.get(Calendar.DAY_OF_MONTH));
            sb.append(' ');
            sb.append(monthList[cal.get(Calendar.MONTH)]);
            sb.append(' ');
            sb.append(cal.get(Calendar.YEAR));
            return sb.toString();
        public void view_image(String FileName)
    }and show it on class ClipCanvas
    Class ClipCanvas
    Merupakan Class yang di gunakan untuk membuat area
    Clip Mata
    import javax.microedition.lcdui.*;
    import java.util.*;
    import java.io.*;
    import java.lang.Math.*;
    import javax.microedition.io.file.*;
    import javax.microedition.io.*;
    class ClipCanvas extends Canvas implements CommandListener, Runnable
      private  Command cmSave = new Command("Save Image Area Crop",Command.SCREEN,1);
      private  Command cmSendMMS = new Command("Send MMS",Command.SCREEN,1);
      private  Command cmHelp = new Command("Help",Command.SCREEN,1);
      private  Command cmExit = new Command("Keluar", Command.SCREEN, 1);
      private Midlet midlet;      // Main midlet
      private Image im,ImageCrop,TempImage = null; // Image to display
      //private Graphics TempGraphics;
      private Random random;    // Get random number
      private int clipx = 0,  clipy = 0,  // View port
                  clipw = 200, cliph = 200; // (clipping region)
      private int old_clipx = 0, old_clipy = 0; // Last clipping region
      private int awalx,awaly;
      private String NamaFile;
      //konstruktor
      public ClipCanvas(Midlet midlet,final String NamaFile,int awalx,int awaly)
        this.midlet = midlet;
        this.NamaFile = NamaFile;
        // Create exit command & listen for events
        this.addCommand(cmSave);
        this.addCommand(cmSendMMS);
        this.addCommand(cmHelp);
        this.addCommand(cmExit);
        // Get random values for starting point
        random = new java.util.Random();
        // Make sure the entire clipping region is
        // visible on the display 
           this.clipx = Math.min((getWidth() - clipw),
                         (random.nextInt() >>> 1) % getWidth());
           this.clipy = Math.min((getHeight() - cliph),
                         (random.nextInt() >>> 1) % getHeight());
          // Create immutable image
               new Thread(new Runnable() {
               public void run(){
               //String NamaFile = NamaFile1;
               InputConnection fileConn = null;
               DataInputStream dis = null;
               try{
               fileConn = (InputConnection)Connector.open(NamaFile,Connector.READ);
               dis = fileConn.openDataInputStream();
               im = Image.createImage(dis); 
               TempImage = Image.createImage(im.getWidth(),im.getHeight());
               dis.close();
                catch (java.io.IOException e)
                  System.err.println("Unable to locate or read .png file");
                  e.printStackTrace();
            }).start();
          this.awalx = awalx;
          this.awaly = awaly;
        setCommandListener(this);
      protected void paint(Graphics g)
        if (im != null)
          //putihin layar
          g.setColor(0xFFFFFF);
          g.fillRect(0,0,getWidth(),getHeight());
          // Clear only the previous clipping region
          g.setColor(255, 255, 255);
          g.fillRect(old_clipx, old_clipy, clipw, cliph);     
          g.drawRect(old_clipx, old_clipy, clipw-1, cliph-1);
          g.drawRect(old_clipx+92, old_clipy+92, 8,8);
          // Set the new clipping region
          g.setColor(255, 255, 255);
          g.setClip(clipx, clipy, clipw, cliph);
          // Draw image 
          g.drawImage(im, awalx, awaly, Graphics.LEFT | Graphics.TOP);
          //draw si rectangle kecil
          g.setColor(0xFF001E);
          g.drawRect(clipx,clipy,clipw-1,cliph-1);
          g.drawRect(clipx+92,clipy+92,8,8);
          Graphics TempGraphics = TempImage.getGraphics();
          TempGraphics.drawImage(im,awalx, awaly,Graphics.LEFT | Graphics.TOP);
        } else
          //putihin layar
          g.setColor(0xFFFFFF);
          g.fillRect(0,0,getWidth(),getHeight());
          //draw si rectangle kecil
          g.setColor(0xFF001E);
          g.drawString("Tekan Tombol Arah !",clipx,clipy,Graphics.LEFT | Graphics.TOP);
      public void commandAction(Command c, Displayable d)
        if (c == cmExit)
          midlet.SelesaiAplikasi();
        else
        if (c == cmSave){
          try {
             ImageCrop = Image.createImage(TempImage,clipx,clipy,clipw,cliph,0);
          } catch(NullPointerException ioe){
            System.err.println("Halo !!!!!");
            return;
          midlet.SaveImage(ImageCrop,NamaFile,awalx,awaly);
      protected void keyPressed(int keyCode)
        // Save the last clipping region
        old_clipx = clipx;
        old_clipy = clipy;
        switch (getGameAction(keyCode))
          case UP:
            // Move clipping region up 3 pixels
            if (clipy > 0)
              clipy = Math.max(0, clipy - 3);
            else
              if (awaly+3 <=0)
                 awaly += 3;
            break;
          case DOWN:
            // Move clipping region down 3 pixels     
            if (clipy + cliph < getHeight())
              clipy = Math.min(getHeight(), clipy + 3);
            else
            if (im.getHeight() > getHeight()){
              if (awaly-3 >=(-1*(im.getHeight()-getHeight())))
                 awaly -= 3;
            break;
          case LEFT:
           // Move clipping region left 3 pixels
           if (clipx > 0)
              clipx = Math.max(0, clipx - 3);
            else
                 if (awalx + 3 <=0)
                   awalx += 3;
          break;
          case RIGHT:
            // Move clipping region right 3 pixels     
            if (clipx + clipw < getWidth())
              clipx = Math.min(getWidth(), clipx + 3);
         else
              if (im.getWidth() > getWidth()){
             if (awalx - 3 >= -1*(im.getWidth()-getWidth()))
               awalx -= 3;
           break;
          case FIRE:
          try {
             ImageCrop = Image.createImage(TempImage,clipx,clipy,clipw,cliph,0);
          } catch(NullPointerException ioe){
            System.err.println("Halo !!!!!");
            return;
          midlet.SaveImage(ImageCrop,NamaFile,awalx,awaly);       
          break;
        repaint();
      public void run(){
    }

  • Servlet - j2me communication

    hi,
    i have written a basic servlet and j2me communication project. servlet gets the command, and increase counter value 1 up. from two different mobile phone emulators, i connect to the servlet. when i send a request to the servlet from one emulator, then counter returns 1. From the other emulator, when i send a request, then counter returns 2. do the two different emulators use the same session of the servlet? what is the servlet's logic? dont the two emulators create their own instance of the servlet?

    First of all, when you post code, please, use the "code" tags.
    I can't test your code but I start to analyse the method startApp() and there is:
    userName = new TextField("LoginID:", userName.getString(), 30, TextField.ANY);The object userName is null so
    userName.getString()throws a NullPointerException for sure!
    Hope this helps.

  • J2ME dictionary code with errors

    Hi,
    i'm getting headache looking for error. im new to J2ME so i don't really understand the real problem. Please healp me to correct the code. i would appreciate very much helps from anyone. Thanks and please help!
    code:
    package util;
    import java.util.*;
    import java.io.*;
    class Word {
    String eng;
    String rus;
    int count;
    public class Dictionary {
    static boolean LARGE_DICTIONARY = true;
    static final int FREQUENCY = LARGE_DICTIONARY ? 0 : 3;
    static final int MAX_LENGTH = LARGE_DICTIONARY ? 64 : 25;
    static final int MAX_FILE_SIZE = 16*1024;
    static int split(int[] words, int[] bestParts, int[] currParts, int offs, int partNo, int minWords) {
    if (++partNo < currParts.length) {
    for (int i = offs+1; i < words.length; i++) {
    currParts[partNo-1] = i;
    minWords = split(words, bestParts, currParts, i, partNo, minWords);
    } else {
    int maxWords = 0;
    for (int i = 0, j = 0; i < currParts.length; i++) {
    int nWords = 0;
    while (j < currParts) {
    nWords += words[j++];
    if (nWords > maxWords) {
    maxWords = nWords;
    if (maxWords < minWords) {
    System.arraycopy(currParts, 0, bestParts, 0, currParts.length);
    minWords = maxWords;
    return minWords;
    public static void main(String[] args) throws Exception {
         BufferedReader in = new BufferedReader(new FileReader("Mueller7GPL.win"));
         String line;
         TreeMap hash = new TreeMap();
    nextLine:
         while ((line = in.readLine()) != null) {
         int i = line.indexOf(' ');
         if (i > 1) {
    for (int j = 0; j < i; j++) {
    char ch = line.charAt(j);
    if (!(ch >= 'a' && ch <= 'z') && !(ch >= 'A' && ch <= 'Z')) {
    continue nextLine;
              Word word = new Word();
              word.eng = line.substring(0, i).toLowerCase();
              boolean firstChar = true;
              int nBrackets = 0;
              StringBuffer buf = new StringBuffer();
              boolean skip = false;
              while (++i < line.length()) {
              char ch = line.charAt(i);
              switch (ch) {
              case '{':
              case '(':
              case '[':
                   nBrackets += 1;
                   continue;
              case '}':
              case ')':
              case ']':
                   nBrackets -= 1;
                   continue;
              case '_':
                   skip = true;
                   continue;
              case ' ':
                   skip = false;
                   if (!firstChar && nBrackets == 0) {
                   buf.append(' ');
                   continue;
              default:
                   if (!skip && nBrackets == 0) {
                   if (Character.isLetter(ch) && ch > 'z') {
                        firstChar = false;
                        buf.append(ch);
                   } else if (!firstChar) {
                        word.rus = buf.toString().trim();
                        int len = word.rus.length();
                        if (len > 2 && len <= MAX_LENGTH ) {
    if (hash.get(word.eng) == null) {
    hash.put(word.eng, word);
                        continue nextLine;
    if (FREQUENCY != 0) {
    byte[] buf = new byte[1025*1024];
    int rc;
    FileInputStream fs = new FileInputStream("samples.txt");
    while ((rc = fs.read(buf)) > 0) {
    for (int i = 0; i < rc; i++) {
    int j = i;
    char ch;
    while (j < rc && (((ch = (char)buf[j]) >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) {
    j += 1;
    if (j > i) {
    String key = new String(buf, i, j-i).toLowerCase();
    Word word = (Word)hash.get(key);
    if (word != null) {
    word.count += 1;
    i = j;
    if (args.length > 0) {
    int nParts = Integer.parseInt(args[0]);
    int partNo = Integer.parseInt(args[1]);
    Iterator iterator = hash.values().iterator();
    char firstLetter = '\0';
    int[] words = new int[26];
    int i = -1;
    while (iterator.hasNext()) {
    Word word = (Word)iterator.next();
    if (word.eng.charAt(0) != firstLetter) {
    firstLetter = word.eng.charAt(0);
    i += 1;
    words[i] += 1;
    int[] currParts = new int[nParts];
    int[] bestParts = new int[nParts];
    currParts[nParts-1] = words.length;
    split(words, bestParts, currParts, 0, 0, Integer.MAX_VALUE);
    iterator = hash.values().iterator();
    i = 0;
    if (partNo > 1) {
    for (int n = bestParts[partNo-2]; i < n; i++) {
    for (int j = words[i]; --j >= 0;) {
    iterator.next();
    TreeMap subset = new TreeMap();
    for (int n = bestParts[partNo-1]; i < n; i++) {
    for (int j = words[i]; --j >= 0;) {
    Word word = (Word)iterator.next();
    subset.put(word.eng, word);
    hash = subset;
         FileOutputStream index = new FileOutputStream("dictionary.idx");
         FileOutputStream out = new FileOutputStream("volume.1");
         Iterator iterator = hash.values().iterator();
         int n = 0;
         int size = 0;
         int totalSize = 0;
    int id = 1;
    String prevWord = null;
    StringBuffer ib = new StringBuffer();
         while (iterator.hasNext()) {
         Word word = (Word)iterator.next();
         if (word.count >= FREQUENCY) {
              StringBuffer sb = new StringBuffer();
    String thisWord = word.eng;
    if (prevWord == null) {
    ib.append(thisWord);
    ib.append(':');
    sb.append(thisWord);
    } else {
    int prefix;
    int len = thisWord.length() > prevWord.length() ? prevWord.length() : thisWord.length();
    if (len > 9) {
    len = 9;
    for (prefix = 0; prefix < len && thisWord.charAt(prefix) == prevWord.charAt(prefix); prefix++);
    if (prefix > 0) {
    sb.append((char)(prefix + '0'));
    sb.append(thisWord.substring(prefix));
    } else {
    sb.append(thisWord);
              sb.append(':');
              sb.append(word.rus);
              //sb.append('\r');
              sb.append('\n');
              byte[] bytes = sb.toString().getBytes();
    if (size + bytes.length > MAX_FILE_SIZE) {
    ib.append(prevWord);
    ib.append('\n');
    index.write(ib.toString().getBytes());
    ib = new StringBuffer();
    ib.append(thisWord);
    ib.append(':');
    out.close();
    out = new FileOutputStream("volume." + ++id);
    size = 0;
              size += bytes.length;
    totalSize += bytes.length;
              n += 1;
    prevWord = thisWord;
              out.write(bytes);
         out.close();
    ib.append(prevWord);
    ib.append('\n');
    index.write(ib.toString().getBytes());
    index.close();
         System.out.println("Words " + n + ", size " + totalSize);

    Can some one take a look at this code and tell me how to get all my jlabels to line up alone side their jtf.
    Because it looks like this the picture in the attached file and this is the code for it:
    public customerPanel()
    // Set the panel with line border
    setBorder(new BevelBorder(BevelBorder.RAISED));
    // Panel p1 for holding labels Name, Street, and City
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(5, 1));
    p1.add(new JLabel("Registration Number:"));
    p1.add(new JLabel("Seating Capacity:"));
    p1.add(new JLabel("Engine Size:"));
    p1.add(new JLabel("Start date of hire"));
    p1.add(new JLabel("Duration of hire"));
    JPanel p2 = new JPanel();
    p2.setLayout(new GridLayout(5, 1));
    p2.add(jtfRegistrationnumber);
    p2.add(jtfSeatingcapacity);
    p2.add(jtfEnginesize);
    p2.add(jtfStartdateofhire);
    p2.add(jtfDurationofhire);
    //JPanel p3 = new JPanel();
    //p3.add(p1, BorderLayout.WEST);
    //p3.add(p2, BorderLayout.NORTH);
    JPanel p4 = new JPanel();
    p4.setLayout(new GridLayout(4, 1));
    p4.add(new JLabel("Manufacture:"));
    p4.add(new JLabel("Model:"));
    p4.add(new JLabel("Mileage:"));
    p4.add(new JLabel("Charge:"));
    JPanel p5 = new JPanel();
    p5.setLayout(new GridLayout(4, 1));
    p5.add(jtfManufacture);
    p5.add(jtfModel);
    p5.add(jtfMileage);
    p5.add(jtfCharge);
    // JPanel p6 = new JPanel();
    // p6.setLayout(new BorderLayout());
    // p6.add(p4, BorderLayout.SOUTH);
    // p6.add(p5, BorderLayout.EAST);
    // Place p1 and p4 into CustomerPanel
    setLayout(new BorderLayout());
    add(p1, BorderLayout.WEST);
    add(p2, BorderLayout.NORTH);
    add(p4, BorderLayout.SOUTH);
    add(p5, BorderLayout.EAST);
    So could someone please help me and correct my code so that each text lable is lined up next to its jtf java text field.

  • How to connect j2me game to another j2me game via gprs

    i create a simple game like tic tac toe, but i still confuse how can i play with my friend via gprs. need help in server configuration, and what connection should i use http connection or socket connection. if anyone know the script for my j2me and server please tell me.

    If you're using MIDP 1, which is what you need if you plan on deploying the game on an available phone, then the only protocol that you can count on being supported is Http. So if you're looking for portability across a large number of devices then that's what you should use (HttpConnection specifically). Also, since there is no push architecture in MIDP 1, you'll need to use the technique called "polling", which means you're clients are going to have to send requests to the server every few seconds to check for updates in the game.
    I actually did a little 2 player tic tac toe to teach myself MIDP, and the code is available at planet source code:
    http://www.planetsourcecode.com/vb/scripts/ShowCode.asp?txtCodeId=3398&lngWId=2
    (If the link doesn't work just make a search for MIDP under the Java section).
    You have to add a line to the JAD file that has the URL of the servlet, or you can replace:
    String url = getAppProperty("TicTacToe.URL");in sendMessage() with a hard-coded string.
    The servlet is very very crude, since I have little experience using Java on the server side and I was more interested in doing the client, and it just links the first two available players and automatically starts a game. But I think it might serve as good starting point for you. And of course, if you are more comfortable with other server-side technologies then you should use them instead of a servlet.

  • J2ME, please give me a scope of it

    Hi, I've been doing application programming using J2SE 1.4 and 1.5. I think I have progressed sufficiently to learn to write software for my Blackberry. Can this be done, if so what are some must-knows of programming for moblie devices. Does J2ME abstract the differences between different cellphones (including blackberry) and offer cross-platform compatibility.
    Also, please point be to some kind of tutorials that introduces me to this stuff.

    There are tutorials on this site (just poke around you'll find them) and forums on J2ME here as well.
    J2ME is basically stripped-down J2SE. Some parts (like, floating point numbers) may not be supported.
    It provides a degree of cross-platform compatibility across devices, but devices are free to support or not support various packages and parts of it, so you can't count on it for 100% compatibility -- you'll still have to do a lot more to support compatibility than you have to for J2SE stuff.
    Also you're going to hit resource limits pretty quick -- once you get past simple "hello world!" programs, you're going to start getting out of memory exceptions a lot more than you're used to with J2SE. At least that was my experience.

  • J2ME problem with threads

    Hi all,
    I would like to ask you for a help. I need to write a small program at my university. I started to write a midlet which function would be to countdown time for sports activities. I woul like to start a new thread - the one that counts down - and at the same time make the main thread sleep. After the "countdown" thread finishes, the main thread wakes up and waits for user input. The problem is that when the "countdown" thread finishes his work, I've got Uncaught exception java/lang/NullPointerException. error and the midlet halts.
    Below you can find the code
    import java.lang.*;
    import java.util.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class intervals extends MIDlet implements CommandListener
    public Display ekran;
    private SweepCanvas sweeper;
    private Form rundy;
    private TextField round0, round1, round2, round3, round4, round5, round6, round7, round8;
    private long czas,x;
    private Command exitCommand;
    private Command addRound;
    private Command delRound;
    private Command start;
    private TextField repeat;
    private Form odliczanie;
    private Alert ostrz;
    Licznik thread;
    String test;
    StringItem test1;
    int parz,i,j,k;
    static int l;
    int ilrund;
    int ilpowt;
    Item sec;
    long sec1;
    public intervals()
        rundy = new Form("Interwa&#322;y sportowe");
        exitCommand = new Command("Wyj&#347;cie", Command.EXIT, 2);
        addRound = new Command("Dodaj","Dodaj rund&#281;", Command.ITEM,1);
        delRound = new Command("Usu&#324;","Usu&#324; ostatni&#261; rund&#281;", Command.ITEM,1);
        start = new Command("Start", Command.ITEM,1);
        odliczanie = new Form("Odliczanie");
        TextField dodaj(TextField kolej)
            kolej=new TextField("Podaj czas (s) rundy "+parz,null, 4, TextField.NUMERIC);//stworzenie nowej instancji do wybierania czasu trwania rundy
            if(rundy.size()==0)
                rundy.insert(rundy.size(),kolej);
                else
                    rundy.insert(rundy.size()-1, kolej);
            return kolej;
        void odliczanie(TextField round)
            monitor m=new monitor();
            k=Integer.parseInt(round.getString());
            ekran.setCurrent(odliczanie);
            thread=new Licznik(k,odliczanie);
            thread.start();
            ekran.setCurrent(rundy);
    public void startApp()// throws MIDletStateChangeException
        rundy.deleteAll();
        repeat = new TextField("Podaj ilo&#347;&#263; powtórze&#324;",null,1,TextField.NUMERIC);
        rundy.addCommand(addRound);
        rundy.addCommand(exitCommand);
        rundy.setCommandListener(this);
        Canvas obrazek = new MyCanvas();
        ekran = Display.getDisplay(this);
        ekran.setCurrent(obrazek);
        czas=System.currentTimeMillis();
        while (System.currentTimeMillis()<czas+1000)
            continue;
        ekran.setCurrent(rundy);
    public void pauseApp()
    public void destroyApp(boolean unconditional)
        notifyDestroyed();
    public void commandAction(Command c, Displayable s)
        if (c == exitCommand)
            destroyApp(false);
            notifyDestroyed();
        else if(c==addRound)
            if(rundy.size()==0)//Sprawdzenie ilo&#347;ci elementów w celu poprawnego wy&#347;wietlania liczby rund w formie
                parz=1;
                else
                parz=rundy.size();
            switch(parz)
                case 1:
                    round0=dodaj(round0);break;
                case 2:
                    round1=dodaj(round1);break;
                case 3:
                   round2= dodaj(round2);break;
                case 4:
                    round3=dodaj(round3);break;
                case 5:
                    round4=dodaj(round4);break;
                default:
                    ostrz=new Alert("Uwaga","Maksymalna liczba rund wynosi 9", null, AlertType.INFO);
                    ostrz.setTimeout(3000);
                    ekran.setCurrent(ostrz);
            if(rundy.size()==1)
                rundy.append(repeat);
                rundy.addCommand(start);
            rundy.addCommand(delRound);
        else if(c==delRound)
            if(rundy.size()!=0)
                rundy.delete(rundy.size()-2);
                if (rundy.size()==1)
                    rundy.deleteAll();
                if(rundy.size()==0)
                    rundy.removeCommand(delRound);
                    rundy.removeCommand(start);
        else if(c==start)
            ilrund=rundy.size()-1;
            if(this.repeat.size()>0)
                ilpowt=Integer.parseInt(this.repeat.getString());
            ekran = Display.getDisplay(this);
            for (i=1; i<=ilpowt;i++)
                odliczanie= new Form("Odliczanie");
                 for (j=0;j<ilrund;j++)
                    switch(j)
                         case 0:
                             odliczanie(round0);
                             break;
                         case 1:
                             odliczanie(round1);
                             break;
                         case 2:
                             odliczanie(round2);
                             break;
                         case 3:
                             odliczanie(round3);
                             break;
                         case 4:
                             odliczanie(round4);
                             break;
                         case 5:
                             odliczanie(round5);
                             break;
                         case 6:
                             odliczanie(round6);
                             break;
                         case 7:
                             odliczanie(round7);
                             break;
                         case 8:
                             odliczanie(round8);
                             break;
    class Licznik extends Thread
        int czas1,k;
        Form forma;
        monitor m;
        public Licznik(int k,Form formap)
            czas1=k;
            forma=formap;
        public synchronized void run()
            while(czas1>0)
                forma.deleteAll();
                forma.append("Czas pozosta&#322;y (s): "+czas1);
                try{Thread.sleep(1000);} catch(InterruptedException e){e.printStackTrace();}
                czas1--;
            if(czas1<=0)
                m.put();
        }and monitor class
    public class monitor
    boolean busy=false;
    synchronized void get()
        if(!busy)
            try
                wait();
            }catch(InterruptedException e){e.printStackTrace();}
        notify();
    synchronized void put()
        if(busy)
            try
            wait();
            }catch(InterruptedException e){e.printStackTrace();}
        busy=true;
        notify();
    }Can anybody help me with this?

    Groovemaker,
    Your Licznik class has a member m of type monitor, which has not been instantiated (in other words is null) hence, when calling m.put() you get NullPointerException. Please also mind, that using Thread.sleep(1000) is not an accurate way of measuring time.
    If I may, please use recommended for Java class naming conventions - some of your names use lower case, while other don't which is confusing to the reader.
    Daniel

  • Order of delivery schedule line counter at schedule agreements from MRP run

    Currently we are using schedule agreements for our long term external suppliers, but we are facing a problem with the order of new delivery schedule lines created during MRP run.
    Because of master data settings like, lot size, rounding value, plan delivery time and planning time fence to set as firm new requirements, multiple schedule lines are created with no order for schedule line counter.
    Does anyone is aware of a BADI, user exit or customizing control to have this schedule line counter in order?
    Thank you
    Daniel Guillen
    IT
    Skyworks Inc.

    Hi,
    Pls put this query in SD fourms  and get immly help because this is technical fourms.
    Anil

Maybe you are looking for