Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

06 July 2011

Java Swing basics

In Java Swing system, below are a few basic concepts you need to understand:
  1. Everything appears on screen is basically a component. JComponent is the Swing superclass of all things that draw on screen. For example, JLabel is a built-in JComponent that displays little text string. What you usually do is to create components objects and install it onto screen or their container.
  2. Frames (JFrame) are the outermost components. A JFrame represents a single window. Each JFrame component has a "content pane" JComponent that contains all components in the frame. You can use frame.getContentPane() to get the content pane. Content pane uses a Layout Manager to size and position its components. Frame has a convenience add() and setLayout() that go to its content pane.
  3. Components are placed inside other components which form a nesting hierarchy from outer to inner components. And each container is behind the components it contains. Layout Manager sizes and places those components according to some 'policies' or 'intents' of the layout. Don't call setSize() yourself, the layout manager controls that! Instead, do call setMinimumSize(), setMaximumSize() or setPreferredSize(), to register a preference before the layout manager lays everything out (before calling pack() / setVisible()).
  4. Three basic layout manager: FlowLayout, BoxLayout, BorderLayout. Flow layout arranges components left-right, top-down like text. Box layout aligns components in a line, either vertically or horizontally. Border layout puts main content in the center and decorate with 4 things around the outsize -- north, south, east, west.
  5. Swing thread, or Event-dispatch thread, Composite pattern and Observer/Observable patterns basically form the underlying architecture of Swing GUI system.
  6. A common technique in Java GUI code is to use an anonymous inner class to create a 'listener' class object and register it using addXXXListener() method to a Observable, e.g a button, on the fly.

05 July 2011

Java String comparison

A common mistake you might make when doing Java string comparison is like this:

String s = "abs";
String t = "cde";

// test for pointer equality, in other words,
// test if s and t are the same object
if (s == t)


What you really want to do might be this:

if (s.equals(t)) // compare characters in two strings


However in python, s==t is actually what you want. When you know too many programming languages, you can easily mess up the syntax and semantics of them accidentally. Be careful.

27 March 2011

[Technote] Saving states from Android Activities

When you start to develop applications on Android devices, managing Activity states definitely is the first major thing to master in order to create reliable, robust Android apps. Here I will simply go through what I have found during developing Android apps myself:

First, you have to think carefully what states are necessary to be retained when Android Activity is destroyed. Usually, the less states you save, the better (because that reduces your Activity start-up time as well as destroying time). For instance, you might not need to save the 'look' of View, because it can always be redrawn/recomputed every time when an Activity comes to live; instead, saving some states necessary for Android to recompute that look, i.e., the current position of the cursor on screen.

Second, you can then think about HOW to save states after determining what to save. Generally, there are three ways to do it (not including saving data on Android internal filesystem or SD card):
  • Using Bundle to save primitive typed (check for Bundle API), temporary data.
  • Using SharedPreferences to save primitive typed, persistent data.
  • Using onRetainNonConfigurationInstance to save temporary object instances.
I personally find the last bullet very useful because the data we want to save cannot always be primitive typed! For more details about the differences and usages of the three approaches, check out here.

To retrieve data you saved, onCreate is a good place for your activity to reload states. According to my experience, onCreate is probably and mostly what you really want, not onResume or onStart otherwise.

A side note for the above: the easiest and best way to test if your management of Activity's life cycle is correct, is to change the orientation of the screen. It should not crash and the behavior should be the same as before orientation.

Last, sometimes what we really want is to have some simple communication mechanism between activities (i.e., the calling activity and the callee activity) instead of saving states, how to achieve that? In the caller activity, call the callee with startActivityForResult, and also implement the onActivityResult method. Then, in the callee, remember to call setResult to set the result to be returned, before the activity is finished.

17 March 2011

[Techonote] Java container anomaly

You can assign a pointer of type sub to a pointer of type super (this is simply a is-a relationship). However, you cannot assign a pointer type container(sub) to a pointer of type container(super) (e.g. List<String> IS NOT a List<Object>).

15 March 2011

[Technote] Caution for Java auto-unboxing

Auto unboxing does not work with == or !=.

For example:

Two List<Integer> a and b, a.get(0) == b.get(0) -- does not unbox. Instead, it does an == pointer comparison between the two Integer objects.

To get what you want, you will do the following:

Use a.get(0).intValue() == b.get(0).intValue() to force the conversion to int. Or you could write a.get(0).equals(b.get(0)) which works for String, Integer, etc.

22 February 2011

[Technotes] Java Inner classes

First thing first, there is some terminology that needs to be explained.

In Java, you can define a class inside another class; such a class is called nested class. Nested classes can be divided into two categories: static or non-static. Static nested classes are simply called static nested classes. Non-static nested classes are called inner classes.

As for nested classes' privileges, inner classes have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class, instead, it can only access to static methods and members of the enclosing (parent) class.

To make the story even more complex, there are 2 other flavors of 'inner classes': local classes and anonymous classes (also called anonymous inner classes). You get to see lots of these two special kinds of inner classes in GUI codes. So you must understand and master them to be able to do GUI programming in Java. To see some concrete examples of these two classes, check out here and there.

In addition, you'd better read the following three web pages carefully before using inner or nested classes:

http://bit.ly/fPoJad - Nested classes introduction
http://bit.ly/dQzVvD - Inner class code example

Finally, to instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

06 February 2011

[Tech notes] How to delete objects in Java?

There is no delete or free keyword in Java. The only thing that can collect the unreferenced memory chunk is garbage collector (GC). To take advantage of that, the best practice is to 'null' out your object reference whenever you want the GC to free that object:


MyObject a = new MyObject();

... /* Do something with object a */

a = null; /* Tell GC to free the memory referenced by a! */

19 May 2010

Can Java have memory leak?

The answer is yes; and it is typically called unintentional object retention.
And this problem actually is not uncommon so that you need to understand what that is and how it could be prevented in your Java programs. Again this problem points out the peril of learning Java as your first and only programming language.
The solution is to NULL out obsolete references as soon as you are sure they will not be dereferenced ever again.

28 April 2010

How to sort a HashMap based on its values?

The trick is to use 'Collections' class and use a LinkedHashMap to hold the the sorted entries inserted in order of insertion.

31 March 2010

Java coding guidelines

http://www.horstmann.com/bigj/style.html
Read it if you want to be a good Java programmer!!!

23 February 2010

How to parse XML document with Java?

You can either use DOM or SAX from Java API. Each interface has its own advantages and disadvantages. SAX is very useful for large XML documents where you only want to get information from them but not modify them.
Check this very nice tutorial out: http://www.totheriver.com/learn/xml/xmltutorial.html
This is where I got to learn how to use DOM and SAX. And I just completed a project by using DOM.

Java Exception Handling

Exceptions can be categorized as checked and unchecked.
It is a good habit to handle checked exceptions with try...catch...finally clause or with throws clause that follows method signature. Sun's Java tutorial has a very nice explanation about exception handling in Java:
http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

08 February 2009

JAVA program

Just this passed Wednesday, I wrote my first JAVA program. It is not an amazing program; it only serves the purpose for practice. Nevertheless, I am happy that again I have accomplished something as the beginning for something bigger in the future to come!!! I will write another program soon that is going to be "VERY USEFUL". I'll explain what useful means 7 days later! hehehee...