Steer clear of Java pitfalls

Three tips to keep you from falling into a Java trap

Though the Java language and platform strive to make programmers' lives easier, unfortunately, as in all systems, overly complex and poorly designed areas crop up. Every other month, I will present workarounds to these pitfalls in this new column, Java Traps.

The book Java Pitfalls (John Wiley & Sons, 2000), written by Eric Monk, J. Paul Keller, Keith Bohnenberger, and myself, defines a pitfall as "code that compiles fine but when executed produces unintended and sometimes disastrous results." This broad definition encompasses improper language usage, overly complex APIs, and less effective implementation options. The book details 50 pitfalls. Here, we will discuss three new ones: two API pitfalls and one long-standing bug. All of these problems arose during real-world development projects.

Pitfall 1: When setSize() doesn't work

Most developers stumble upon pitfalls sequentially as they become more experienced with Java. The setSize() pitfall usually presents itself soon after Java developers begin serious GUI development -- specifically, when they first attempt to set the size of a custom component. BadSetSizeApplet below intends to create a simple custom button, sized at 100 pixels by 100 pixels. Here is the code to create our custom button:

class CustomButton extends Button
{
    public CustomButton(String title)
    {
        super(title);    
        setSize(100,100);
    }
}

In the constructor, developers often assume that they can use setSize()(width, height), as they do when sizing a frame. But this code will only work in certain situations -- here, setSize() will fail to correctly size the component. When we place our custom button in the applet with other components using a simple grid layout, we get the results below. Our button is 66 by 23, not 100 by 100! What happened to our call to setSize()? The method was executed, of course. However, it did not give the final word on the size of our component.

1 2 Page
Join the discussion
Be the first to comment on this article. Our Commenting Policies
See more