HTML Markup | JavaScript | Java | Home & Links

Tutorial 12 - Advanced Swing

This tutorial covers advanced Java Swing topics such as inner class event listeners using inner classes, the MVC architecture which factors worker from GUI code, adding widgets dynamically, mouse events and specialized containers. Menus, toolbars and popups are also covered. Basics|Intermediate

Advanced Event Listeners

A difficulty with the basic event listening technique (ie event sharing) is that it becomes awkward to program for many buttons and widgets. Extended if statements or switch constructs can make code hard to maintain. There are better ways!

Inner (ie nested) class event handlers allow handler routines to be written for specific objects. For example, instead of using the addActionListener(this) method for several buttons you can have each button call its own inner class. Function code can still be mixed into GUI code. See the list of other event listeners.

NOTE: The implements clause is now placed in each inner class header and not in the main class header. Also the listener registration is of a specific Listener_class object, not the generic this.

Anonymous inner classes have no name (hence no name conflict) and are used when only one instance of the class is required. They also do not have constructors. Anonymous inner classes are most often found in event listeners with very simple actions. Beware! Anonymous listeners intermix action code with the GUI object. This is contrary to the separation of worker code from GUI that is a part of clean design. Avoid this construction if possible.

As event classes are interfaces, all methods within that event must be implemented. Adapter classes provide default do-nothing methods which you can chose to override. Here is a short example using the WindowAdapter class to avoid coding all window events.

Model-View-Controller Architecture

Model-View-Controller (MVC) architecture uses a controller module to factor data storage and manipulation code from GUI design code. The controller module ties event listeners in the view module to their actions in the model module. These three object modules can be designed at different times by different programmers. Good programming practice implies private properties with public accessor methods for those needing access from outside their container.

MyMVC is a very simple example of MVC design that has no data change requiring GUI update. The model object contains the run-time actions for the application. It includes methods for exit(), run(), about() and help() which are common to many utilities. The view object requires methods to build the listeners. buttonActionListeners() includes addActionListener() and a setActionCommand(string) which is used to pass a reference of the pressed button. The view object constructor accepts a string that incorporates the utility title. The controller module uses getActionCommand() to call the correct action method in the model.

When model/view interaction is required, will the model push the change or will the view pull it? The choice requires one module to be aware of the other which violates the concept of reusability. MyMVC2 is a simple button press counter demo that uses the controller to isolate the updating interaction. A Simple MVC Demo uses a different technique to work around this issue.

Dynamically Adding Widgets

Many applications need to add one or more widgets (buttons, textareas, etc.) on a dynamic basis with a "Create" action. AddWidget is a demo that adds a set of buttons as an array.

Mouse Events

There are three types of mouse events: motion, wheel and button clicks. Each has their own listener but adapters can be used to react to combined events. Oracle's Listener Tutorial has examples of many mouse event situations. mouseMotionDemo is my simplified example that uses MVC design principles and adds a status bar using BorderLayout.

NOTE: Swing does not have a built-in StatusBar class.

Tables and Trees

Tables represent data in a row/column two dimensional grid format. The constructor is JTable(data,headers) where data is a two dimension string and headers is a one dimension string. SimpleTable is a demo. Refer to the Oracle tutorial for more complete information.

Trees allow visualization, traversal and manipulation of hierarchical information (ie. parent-children) much easier. Trees consist of nodes. Common examples of trees are file directories and organizational charts. The constructor is JTree(objVar) where objVar can be one of Hashtable, Object, TreeNode, TreeModel or Vector. MyTree is a demo which uses a hashtable to hold the actual tree. Refer to the Oracle tutorial for more complete information.

Panes: Scrolled and Layered

Scrolled panes establish scroll bars for moving the displayed area in lists, textareas and other components. If you wish a scrollbar policy other than 'display scrollers when needed' read Scroll Bar Policies. As an example, to add scrollbars to a text area:

Layered panes allow components such as buttons to be overlapped or layered. A simple example is:

Panes: Split and Tabbed

Split panes allow you to place two components side by side in a single pane. It can also split the pane horizontally. A simple example of a split pane is:

Tabbed panes allow a multilayered pane with tabs for the user to access the desired layer. Each tab contains a single component. A simple example of a tabbed pane is:

MenuBars, ToolBars, PopUps

Dropdown/pullout menu bars are menus similar to those that appear across the top of most Windows programs. The menu bars are constructed from the JMenuBar class. Menus (aka bar items) are constructed from the JMenu class and menu items from the JMenuItem class. Item separators can either be added to a menu with addSeparator() or inserted with insertSeparator(posn). Menu items can be disabled (grayed out) with setEnabled(false) and tested with isEnabled(). Menu items can have a hotkey shortcut added by using setMnemonic(char). Accelerator keys are added with setAccelerator(). The menubar is added to the main frame by using this.setJMenuBar(obj). MyMenu demonstrates many of the features of the menu classes including mnemonics, accelerators keyed to platform, checkbox & radiobutton items and icons.

Dockable toolbars can be constructed from the JToolBar class. JToolBar(SwingConstants.VERTICAL) overrides the default orientation. The add() method adds components which are often icons. setFloatable(bool) and setRollover(bool) alter the toolbar's look. Toolbars are always fully exposed. MyToolBar demonstrates features of the toolbar class including action classes.

Context sensitive popup menus are revealed by some user action (such as right click) and look similar to a dialog box. MyPop demonstrates JPopupMenu and some features of the popup menu classes including specialized listeners.

Tutorial Source Code

Obtain source for MyMVC, MyMVC2, AddWidget, MouseMotionDemo, MyTree, SimpleTable, Audio, MyMenu, MyPop, MyToolBar here.

JR's HomePage | Comments [jatutorc.htm:2014 04 04]