4. Memory Management

For the most part, memory management is automatically taken care of by the Java garbage collector. But since wxWidgets is a C++ library, there are cases when manual memory management must be performed. This is usually caused by the fact that the C++ objects were designed to be created on the stack, thus getting automatically destroyed when the stack object goes out of scope. Because Java does not have an equivalaent of stack objects, they must be manually handled.

4.1. Dialog Boxes

Destroy() is a method off of wxWindow and normally does not need to be called. A parent window will call Destroy() on all of its children windows. But transient windows such as dailog boxes and all their children (wizards, etc.), must be explicity destroyed after use by calling Destroy(). Failure to destroy a dialog will lead to a memory leak at best and possibly erratic program behaviour. Here is an example of how a dialog may be used:

public void AskUser()
    MyAskDialog dlg = new MyAskDialog(...);
    if (dlg.ShowModal() == wxID_OK)
        // ...
    // else: dialog was cancelled or some another button pressed


4.2. Drawing Contexts

delete() is a method that all wxWidgets Java objects have. It calls the destructor on the wrapped C++ class. Normally this does not need to be called, but drawing contexts are special since they are intended to be used as stack objects. Therefore, you must call delete() prior to the end of the method where it is used. For example, to handle a paint event, the following skeletal event handler may be used:

class OnPaint implements wxPaintListener
    public void handleEvent(wxPaintEvent event)
        wxPaintDC dc = new wxPaintDC(/* wxWindow */);

        // ... perform operations on drawing context ..

        // dc is normally a stack object in C++, so make sure to
        // delete it as soon as you are done with it.  Do NOT let
        // the garbage collector do it automatically.