Toolbar Toggle Swing Example

Started playing with Swing this last week and am finding it challenging and fun.

While learning the API, I came across a rather interesting problem where I needed to toggle a tool bar from being displayed in a window via a pop-up menu (regardless of whether it is embedded in the main window or dragged out in its own dialog window). For example:

One Window (where the main window and tool bar are one)

One Window

Two Windows (where the main window and tool bar are separated)

Two Windows

In my case, I needed to turn the tool bar on and off via a pop-up menu for both cases shown mentioned above. Here is a screen shot of the pop-up menu:

Pop-up Menu

Turns out, this proved to be a rather difficult problem especially when the tool bar was popped out from the main window. My solution came about by adding a listener to my JCheckBoxMenuItem object:

Pop-up Menu Code

…which would then call my showToolBar method:

Show Toolbar Method

Here is the full source code in case you want to run the example yourself:

Simply download the zip file, extract the *.java file, compile, and execute. The only compilation error you should have is the package name when running locally.

I would be interested to know if the code I wrote (where I check for correct parentage before disposing the tool bar window) is sound or not. Perhaps there is a smarter way to tackle this problem? In my tests, it seems to work fine without any flaws.

Friday, June 8th, 2007 Software

No comments yet.

Leave a comment

You must be logged in to post a comment.

Search

 

Categories