16. Graphical User Interfaces

16.9. Menus and Scroll Panes

Pop-up and pull-down menus allow an application or applet to grow in complexity and functionality without cluttering its interface. Menus are hierarchical in nature. A particular menu is divided into a number of menu items, which can themselves be further subdivided. Java makes it simple to implement menus.

A JMenuBar is an implementation of a menu bar—a horizontal list of names that appears at the top of a window (Fig. 13.31).

 

 

Menubar

 

 

Menu Separator MenuItem


 

 

 

 

 

 

 

Figure 13.31: An application with a menu bar that is showing its edit menu. The edit menu contains a cascading drop-down menu that can show recent cuts.

 

 

Submenu

 

 

 

Almost all applications have a menu bar. To construct a menu, you add JMenu objects to a JMenuBar. A JMenu is essentially a clickable area on a menu bar that is associated with a JPopupMenu, a small window that pops up and displays the menu’s JMenuItems. A menu can also contain JSeparators, which are dividers that can be placed between menu items to organize them into logical groupings.

Adding a Menu Bar to an Application

It is easy to create menus in Swing. The process involves three steps, although you needn’t perform them in this order:

Create the individual JMenuItems.

Create a JMenu and add the JMenuItems to it.

Create a JMenuBar and add the JMenus to it.

For example, suppose you’re building the interface for a text editor. A text editor typically contains at least two standard menus. The file menu is used to create new documents, open and close files, save your document, and so on. The edit menu is used to cut and paste selected text from the document.

Here’s how you would create the file menu for this program. First, you create a menu bar and make it the menu bar for the application’s JFrame or for the JApplet. This is usually done in the application’s constructor or in the applet’s init() method:

,,

 

J

The next step involves creating and adding menus and menu items to the menu bar. This is also usually done in the constructor or the init()

 

method. If the menu is large, you should break this task into subtasks and define a method for each subtask.

Here’s the definition of the file menu for our simple text editor:

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

J

The first two statements in the method create the file menu and add it to the menu bar. The rest of the statements create the individual menu items that make up the file menu. Note the use of a separator item after the save item. This has the effect of grouping the file-handling items (open and save) into one logical category and distinguishing them from the quit item. A separator is represented as a line in the menu (Fig. 13.31).

Note that each menu item is given an ActionListener. As we’ll see shortly, action events for menu items are handled the same way as action events for buttons. Finally, note how the setEnabled() method is used to disable both the open and save menu items. Implementation of these actions is left as an exercise.

Menu Hierarchies

Menus can be added to other menus to create a hierarchy. For example, the edit menu will include the standard cut, copy, and paste menu items. Some edit menus also contain an “Undo” item, which can be used to undo

 

the last editing operation that was performed. In other words, if you cut a piece of text, you can undo that operation and get that cut back. Many editors seem to allow just a single undo. If you cut two pieces of text, the first piece is lost to the user to undo. This can be an issue, especially if you didn’t mean to do the first cut.

To help remedy this type of situation, let’s add a feature to our editor that will keep track of cuts by storing them in a Vector. This function will be like an “Unlimited Undo” operation for cuts. For this example, we won’t place any limit on the size of the vector. Every cut the user makes will be inserted at the beginning of the vector. To go along with this feature we need a menu that can grow dynamically during the program. Each time the user makes a cut, the string that was cut will be added to the menu.

This kind of menu should occur within the edit menu, but it will have its own items. This is a menu within a menu (Fig. 13.31), an example of a cascading drop-down menu. The edit menu itself drops down from the menu bar, and the recent cuts menu drops down and to the right of where its arrow points. The following method was used to create the edit menu:

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

J

The main difference between this method and the one used to create the file menu is that here we insert an entire submenu as one of the items in the edit menu. The cutsMenu will be used to hold the strings that are cut from the document. Initially, it will be empty.

Handling Menu Actions

Handling JMenuItem actions is no different from handling JButton actions. Whenever a user makes a menu selection, an ActionEvent is generated. Programs that use menus must implement the action- Performed() method of the ActionListener interface. In the text ed- itor example, there are a total of six enabled menu items, including the

 

recent cuts menu. This translates into a large if-else structure, with each clause handling a single menu item.

The following actionPerformed() method is used to handle the menu selections for the text editor:

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Default logic


J

The method begins by getting the source of the ActionEvent and cast- ing it into a JMenuItem. It then checks each case of the if-else structure. Because the actions taken by this program are fairly short, they are mostly coded within the actionPerformed() method itself. However, for most programs it will be necessary to write a separate method corresponding to each menu item and then call the methods from actionPerformed().

Our text editor’s main task is to implement the cut/copy/paste func- tions, which are simple to do in Java. The text that’s being edited is stored in a JTextArea, which contains instance methods that make it very easy to select, insert, and replace text. To copy a piece of text, the program need only get the text from the JTextArea (getSelectedText()) and assign it to the scratchpad, which is represented as a String. To paste a piece of text, the program inserts the contents of the scratchpad into the JTextArea at the location marked by the caret, a cursor-like character in the document that marks the next insertion point.

The structure of this if-else statement is significant. Note how the de- fault case of the if-else is designed. We are using the last else clause as a “catch all” condition to catch and handle selections from the cutsMenu. All of the other menu items can be referred to by name. However, the menu items in the cutsMenu are just snippets of a string that the user has previously cut from the text, so they can’t be referenced by name. Luckily, we don’t really need to. For any JMenuItem, the getActionCommand()

 

method returns its text, which in this case is the previously cut text. So we just assign the cut text from the menu to the scratchpad.

 

 

 

 

 

 

Handling Previously Cut Text

The most difficult function in our program is the cut operation. Not only must the selected text be removed from the document and stored in the scratchpad, but it must also be inserted into the vector that is storing all the previous cuts. The addRecentCut() method takes care of this

last task. The basic idea here is to take the cut string and insert it at the Algorithm design

beginning of the vector, so that cuts will be maintained in a last-in–first- out order. Then the cutsMenu must be completely rebuilt by reading its entries out of the vector, from first to last. That way the most recent cut will appear first in the menu:

,

 

 

 

 

 

 

 

 

 

The recentCuts Vector stores the cut strings. Note the use of the insertElementAt() method to insert strings into the vector and the elementAt() method to get strings from the vector. (You may find it helpful to review the section on vectors in Chapter 9.)

Note also how menu items are removed and inserted in menus. The cutsMenu is reinitialized, using the removeAll() method. Then the for loop iterates through the strings stored in the vector, making new menu items from them, which are then inserted into the cutsMenu. In this way, the cutsMenu is changed dynamically each time the user cuts a piece of text from the document.

Adding Scrollbars to a Text Area

The design of the SimpleTextEditor class is summarized in Fig- ure 13.32 and its complete implementation is shown in Figure 13.33.


 

 

 

 

 

 

 

 

 

Figure 13.32:Design of the

SimpleTextEditor.

 

,,

import j avax . swing . ;

import j ava . awt . ;

import j ava . awt . event . ;

import j ava . u t i l . Vector ;

 

public c l a s s Simple Text Editor extends JFrame implements Action Listener

private JMenuBar mBar = new JMenuBar ( ) ;// C r e a t e t h e menu b a r

private JMenu fileMenu , editMenu , cutsMenu ;// Menu r e f e r e n c e s a n d i t e m s private JMenuItem cut Item , copyItem , paste Item , s e l e c t I t e m , recentcut I tem ; private JMenuItem quit Item , openItem , save Item ;// F i l e i t e m s

private JText Area display = new JText Area ( ) ; // H e r e s w h e r e t h e e d i t i n g o c c u r s

private S t r i n g scratch Pad = ”” ;// S c r a t c h p a d f o r c u t / p a s t e

private Vector recent Cuts = new Vector ( ) ;

 

public Simple Text Editor ( )

super ( Simple Text Editor ) ;// S e t t h e wi n do w t i t l e

t h i s . get Content Pane ( ) . set Layout ( new BorderLayout ( ) ) ;

t h i s . get Content Pane ( ) . add ( Center , display ) ;

t h i s . get Content Pane ( ) . add ( new JS c r o l l P a n e ( display ) ) ; display . setLineWrap ( t rue ) ;

t h i s . setJMenuBar ( mBar ) ;// S e t t h i s p r o g r a m s menu b a r

init File Menu ( ) ;// C r e a t e t h e m e n u s

init Edit Menu ( ) ;

} // S i m p l e T e x t E d i t e r ( )

private void init Edit Menu ( )

editMenu = new JMenu ( Edit ) ;// C r e a t e t h e e d i t menu mBar . add ( editMenu ) ;//a n d a d d i t t o menu b a r cut Item = new JMenuItem ( ”Cut” ) ;// C u t i t e m

cut Item . add Action Listener ( t h i s ) ; editMenu . add ( cut Item ) ;

copyItem = new JMenuItem ( ”Copy” ) ;// Co p y i t e m

copyItem . add Action Listener ( t h i s ) ; editMenu . add ( copyItem ) ;

paste Item = new JMenuItem ( Paste ) ;// P a s t e i t e m

paste Item . add Action Listener ( t h i s ) ; editMenu . add ( paste Item ) ;

editMenu . addSeparator ( ) ;

s e l e c t I t e m = new JMenuItem ( S e l e c t All ) ; // S e l e c t i t e m

s e l e c t I t e m . add Action Listener ( t h i s ) ; editMenu . add ( s e l e c t I t e m ) ;

editMenu . addSeparator ( ) ;

cutsMenu = new JMenu ( Recent Cuts” ) ;// R e c e n t c u t s s u b m e n u

editMenu . add ( cutsMenu ) ;

} // i n i t E d i t M e n u ( )

private void init File Menu ( )

file Menu = new JMenu ( F i l e ) ;// C r e a t e t h e f i l e menu

mBar . add ( file Menu ) ;//a n d a d d i t t o t h e menu b a r

openItem = new JMenuItem ( ”Open” ) ;// Ope n i t e m

openItem . add Action Listener ( t h i s ) ;

openItem . set Enabled ( fa l s e ) ; file Menu . add ( openItem ) ;

save Item = new JMenuItem ( Save” ) ;// S a v e i t e m

\J

Figure 13.33: A menu-based SimpleTextEditor application, Part I.

 

,,

save Item . add Action Listener ( t h i s ) ; save Item . set Enabled ( fa l s e ) ;

file Menu . add ( save Item ) ;

file Menu . addSeparator ( ) ;// L o g i c a l s e p a r a t o r quit I tem = new JMenuItem ( Quit ) ; // Q u i t i t e m quit I tem . add Action Listener ( t h i s ) ;

file Menu . add ( quit I tem ) ;

// i n i t F i l e M e n u ( )

public void action Performed ( ActionEvent e )

JMenuItem m = ( JMenuItem ) e . get Source ( ) ; // G e t s e l e c t e d menu i t e m

i f ( m == quit I tem )// Q u i t

dispose ( ) ;

e ls e i f (m == cut Item )// C u t t h e s e l e c t e d t e x t

scratch Pad = display . ge t Se l e c t e d T e xt ( ) ; // Co p y t e x t t o s c r a t c h p a d

display . replace Range ( ”” ,//a n d d e l e t e

display . g e t S e l e c t i o n S t a r t ( ) , //f r o m t h e s t a r t o f t h e s e l e c t i o n

display . get Selection End ( ) ) ;//t o t h e e n d

addRecentCut ( scratch Pad ) ;// Add t h e c u t t e x t t o t h e c u t s menu

e ls e i f (m == copyItem )// Co p y t h e s e l e c t e d t e x t t o t h e s c r a t c h p a d

scratch Pad = display . ge t Se l e c t e d T e xt ( ) ;

e ls e i f (m == paste Item )// P a s t e t h e s c r a t c h p a d t o t h e d o c u m e n t a t c a r e t

display . i n s e r t ( scratch Pad , display . ge t Ca r e t Po s i t io n ( ) ) ; // p o s i t i o n

e ls e i f ( m == s e l e c t I t e m )

display . s e l e c t A l l ( ) ;// S e l e c t t h e e n t i r e d o c u m e n t

e ls e

JMenuItem item = ( JMenuItem ) e . get Source ( ) ; // D e f a u l t i s c u t s M e n u

scratch Pad = item . getActionCommand ( ) ; // P u t c u t b a c k i n t h e s c r a t c h p a d

}

// a c t i o n P e r f o r m e d ( )

private void addRecentCut ( S t r i n g cut ) recent Cuts . insert Element At ( cut , 0 ) ; cutsMenu . removeAll ( ) ;

for ( in t k = 0 ; k < recent Cuts . s i z e ( ) ; k++) JMenuItem item =

new JMenuItem ( ( S t r i n g ) recent Cuts . elementAt ( k ) ) ; cutsMenu . add ( item ) ;

item . add Action Listener ( t h i s ) ;

}

} // a d d R e c e n t C u t ( )

public s t a t i c void main ( S t r i n g args [ ] )

Simple Text Editor f = new Simple Text Editor ( ) ; f . s e t S i z e ( 3 0 0 , 2 0 0 ) ;

f . s e t V i s i b l e ( t rue ) ;

f . addWindowListener ( new WindowAdapter ( )

public void windowClosing ( WindowEvent e ) System . e x i t ( 0 ) ;// Q u i t t h e a p p l i c a t i o n

}

} ) ;

} // m a i n ( )

// S i m p l e T e x t E d i t o r

\J

Figure 13.33: (continued) The SimpleTextEditor, Part II.

 

 

Scrollbars


It uses a BorderLayout, with the JTextArea placed at the center. Note how simple it is to add scrollbars to the text area:

,,

 

 

J

This statement creates a JScrollPane and adds it to the application’s container. A JScrollPane is one of Swing’s scrollbar classes. Its function is to manage the viewing and scrolling of a scrollable component, such as a JTextArea. A JScrollPane is actually a container, which is why it takes the display as an argument. The display is being added to the JScrollPane.

Just about any Component can be added to a JScrollPane. Once a component is added, the scroll pane will manage the scrolling functions for the component. The default constructor used in this example takes a

single Component parameter. This refers to the scrollable component, in this case to the JTextArea. Another constructor that you might use takes the following form:

,,

 

J

The two integers refer to the vertical and horizontal scrolling policies. These cover properties such as whether the scrollbars are always present or just as needed. The default policy is to attach scrollbars to the compo- nent only when needed. Thus, to see the scrollbars in the SimpleText Editor, you would have to shrink the window to the point where all of the text cannot be viewed (Fig. 13.34). Because the text area in this example is wrapping the text, the horizontal scrollbar will never be needed.

 

 

Figure 13.34: The scrollbars ap- pear on the text area only when they are needed. In this case, only a vertical scrollbar is necessary.


SELF-STUDY EXERCISES

EXERCISE 13.9 Modify the addRecentCut() method so it limits the cuts stored in the vector to the last ten cuts.

EXERCISE 13.10 Modify the addRecentCut() method so that it doesn’t duplicate cuts already stored in the vector. (Hint: Use the indexOf(String) method in the Vector class.)