分類彙整: Java

J2ME: Textbox

Adopt from

http://www.java2s.com/Code/Java/J2ME/TextBoxMIDlet.htm

http://www.j2medev.com/api/midp/javax/microedition/lcdui/TextBox.html


Constructor Detail

TextBox

public TextBox(String title,
               String text,
               int maxSize,
               int constraints)

Creates a new TextBox object with the given title string, initial contents, maximum size in characters, and constraints. If the text parameter is null, the TextBox is created empty. The maxSize parameter must be greater than zero. An IllegalArgumentException is thrown if the length of the initial contents string exceeds maxSize. However, the implementation may assign a maximum size smaller than the application had requested. If this occurs, and if the length of the contents exceeds the newly assigned maximum size, the contents are truncated from the end in order to fit, and no exception is thrown.

Parameters:

title - the title text to be shown with the display
text - the initial contents of the text editing area, null may be used to indicate no initial content
maxSize - the maximum capacity in characters. The implementation may limit boundary maximum capacity and the actually assigned capacity may me smaller than requested. A defensive application will test the actually given capacity with getMaxSize().
constraints - see input constraints

Throws:

IllegalArgumentException - if maxSize is zero or less
IllegalArgumentException - if the constraints parameter is invalid
IllegalArgumentException - if text is illegal for the specified constraints
IllegalArgumentException - if the length of the string exceeds the requested maximum capacity

Java: ItemStateListener and CommandListener

Adopt from

http://developers.sun.com/mobility/midp/articles/event/


For ItemStateListener

        // an anonymous class       
        ItemStateListener listener =
        new ItemStateListener() {
            java.util.Calendar cal =
              java.util.Calendar.getInstance(
        java.util.TimeZone.getDefault());

            public void itemStateChanged(Item item) {
                cal.setTime(((DateField)item).getDate());
                System.out.println("\nDate has changed");
            }
        };

        // register for events
        this.setItemStateListener(listener);

For CommandListener

        //Add and Activate these commands on this form
        this.addCommand(backCmd);
        this.addCommand(saveCmd);
        this.addCommand(addCmd);
        this.addCommand(autoScheduleCmd);
        this.setCommandListener(this);

J2ME : SVG Support

Adopt from

http://developers.sun.com/mobility/midp/articles/s2dvg/index.html


1. Create an SVG file

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN"
    "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">
<svg preserveAspectRatio="xMidYMid meet"
        viewbox="10 10 130 55" width="150.0" height="75.0">
    <rect x="25" y="25" transform="translate(75 36.375)
        rotate(15) translate(-70 -35.375)" fill="#00007E"
        width="100" height="22.75" stroke="#000000" stroke-width=".5"/>
    <rect x="25" y="25" fill="#FF9800" width="108.5"
        height="22.75" stroke="#000000" stroke-width=".5"/>
    <text x="30" y="40" fill="#00007E" stroke="#FFFFFF"
        stroke-width=".33" xml:space="preserve">Hello brave world.</text>
</svg>

2. Define a ScalableImage object

// retain a reference the specified image
        ScalableImage scalableImage;
        // retain an instance of a scalable graphics
        ScalableGraphics scalableGraphics;
        public M2GCanvas( ScalableImage inImage )
        {
            scalableImage = inImage;

            // create the scalable graphics instance
            scalableGraphics = ScalableGraphics.createInstance();
        }

3. Paint on graphics

public void paint( Graphics g )
        {
            // clear the display
            g.setColor( 255, 255, 255 );
            g.fillRect( 0, 0, getWidth(), getHeight() );
            // bind our scalable graphics to the given graphics
            scalableGraphics.bindTarget( g );

            // render at fixed position and size
            scalableImage.setViewportWidth( 50 );
            scalableImage.setViewportHeight( 75 );
            scalableGraphics.render( 5, 50, scalableImage );

            // again at different position and size
            scalableImage.setViewportWidth( 100 );
            scalableImage.setViewportHeight( 150 );
            scalableGraphics.render( 80, 5, scalableImage );

            // again at size that varies with the canvas size
            scalableImage.setViewportWidth( getWidth()-20 );
            scalableImage.setViewportHeight( getHeight()-20 );
            scalableGraphics.render( 0, 0, scalableImage );

            // release the graphics context
            scalableGraphics.releaseTarget();
        }

Java: Touch Screen Phones

Adopt from

http://javabyexample.wisdomplug.com/java-applications/38-j2me/49-mobile-game-development-with-j2me.html?start=6


override the pointerPressed() method

protected void pointerPressed(int X, int Y)
{
   int width = getWidth();
   int height = getHeight();
   int offsetX = (width - 2) / 3;
   int offsetY = (height - 2) / 3;
   cursorX = offsetX / X;
   cursorY = offsetY / Y;
   keyPressed(getKeyCode(FIRE_PRESSED));
}

Java: Features Removed from C and C++

Adopt from

http://java.sun.com/docs/white/langenv/Simple.doc2.html


No more Typedefs, Defines, or Preprocessor

No more Structures or Unions

No Enums

No more Functions

No more Multiple Inheritance

No more Goto statements

No more Operator Overloading

No more Automatic Coercions

No more Pointers

 

Replaced by

Object-Oriented Programming

Use break and continue

Explicity using a cast

Java: The switch Statement

Adopt from

http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html


class SwitchDemo2 {
    public static void main(String[] args) {

        int month = 2;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                numDays = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                numDays = 30;
                break;
            case 2:
                if ( ((year % 4 == 0) && !(year % 100 == 0))
                     || (year % 400 == 0) )
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                System.out.println("Invalid month.");
                break;
        }
        System.out.println("Number of Days = " + numDays);
    }
}

Java: Stream

Referernce

http://developers.sun.com/mobility/midp/articles/persist/

http://d.android.com/reference/java/io/DataOutputStream.html

http://java.sun.com/j2se/1.4.2/docs/api/java/io/DataOutputStream.html

http://www.cplusplus.com/reference/iostream/


In Java

A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.

OutputStream

The base class for all output streams. An output stream is a means of writing data to a target in a byte-wise manner. Most output streams expect the flush() method to be called before closing the stream, to ensure all data is actually written through.

OutputStream

000101010101001 –writing into –> a target

ByteArrayOutputStream

01010101 00101010 – writing into –> ByteArray

DataOutputStream

Wraps an existing OutputStream and writes typed data to it. Typically, this stream can be read in by DataInputStream. Types that can be written include byte, 16-bit short, 32-bit int, 32-bit float, 64-bit long, 64-bit double, byte strings, and MUTF-8 encoded strings.

DataOutputStream(ByteArrayOutputStream)

Typed data(A B) –convert into –> 01000001 01000010 – writing into –> ByteArray

In C++

A stream is an abstraction that represents a device on which input and ouput operations are performed. A stream can basically be represented as a source or destination of characters of indefinite length.

Streams are generally associated to a physical source or destination of characters, like a disk file, the keyboard, or the console, so the characters gotten or written to/from our abstraction called stream are physically input/output to the physical device. For example, file streams are C++ objects to manipulate and interact with files; Once a file stream is used to open a file, any input or output operation performed on that stream is physically reflected in the file.

Java: Dates

Adopt from

http://www.javaworld.com/jw-12-2000/jw-1229-dates.html?page=1

http://www.tutorialspoint.com/java/java_date_time.htm

http://www.tutorialhero.com/tutorial-70-java_date.php


import java.util.*;
import java.text.*;

class DateDemo {
   public static void main(String args[]) {

       Date dNow = new Date( );
       SimpleDateFormat ft =
       new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

       System.out.println("Current Date: " + ft.format(dNow));
   }
}

//Output: Sun 2004.07.18 at 04:14:09 PM PDT

------------------------------------------------------------

// simple way to get a specific point in time
GregorianCalendar cal = new GregorianCalendar(tz);
cal.set(2009, Calendar.DECEMBER, 31, 20, 15, 00);
cal.set(Calendar.MILLISECONDS, 0);
Date d = cal.getTime();

/**
* Calculates midnight of the day in which date lies with respect
* to a time zone.
**/
public Date midnight(Date date, TimeZone tz) {
  Calendar cal = new GregorianCalendar(tz);
  cal.setTime(date);
  cal.set(Calendar.HOUR_OF_DAY, 0);
  cal.set(Calendar.MINUTE, 0);
  cal.set(Calendar.SECOND, 0);
  cal.set(Calendar.MILLISECOND, 0);
  return cal.getTime();
}

/**
* Adds a number of days to a date. DST change dates are handeled
* according to the time zone. That's necessary as these days don't
* have 24 hours.
*/
public Date addDays(Date date, int days, TimeZone tz) {
  Calendar cal = new GregorianCalendar(tz);
  cal.setTime(date);
  cal.add(Calendar.DATE, days);
  return cal.getTime();
}

---------------------------------------------------------------------------

private DateField dfDate = new DateField("Date is: ", DateField.DATE);

---------------------------------------------------------------------------

Date d = new Date();

Long l = d.getTime();

Java: extends Keyword

Reference from

http://xahlee.org/java-a-day/extend.html

http://xahlee.org/java-a-day/inheritance_constructers.html

http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#41652


Example: Basic

class A{

    Method1(){//Something};

    Method2(){//Something};

}

class B extends A{

    Method1(){//Something}; //Override the existing method

    Method3(){//Something}; //New method

}

public class C{

    A a = new A;

    a.Method1();

    a.Method2();

    B b = new B;

    b.Method1(); //Difference from a.Method1();

    b.Method2(); //Same as a.Method2();

    b.Method3();

}

Example: The Constructor

class B {
   int x;
   B() { } // a constructor
   B( int n ) { x = n; } // a constructor
   int returnMe() { return x; }
}

class C extends B {
}

or this

class B {
    int x;
    B( int n ) { x = n; } // a constructor
    int returnMe() { return x; }
}

class C extends B {
    C () { super(0); } // a constructor
    C (int n) { super(n); } // a constructor
}

Java Spec

8.8.7 Default Constructor If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided: * If the class being declared is the primordial class Object, then the default constructor has an empty body. * Otherwise, the default constructor takes no parameters and simply invokes the superclass constructor with no arguments. A compile-time error occurs if a default constructor is provided by the compiler but the superclass does not have an accessible constructor that takes no arguments.