Menus
§
Menu
– forms an integral and indispensable part of the modern GUI. They give the
user access to a program’s core functionality.
§ The JavaFX menu system supports several key
elements, including
o
The
menu bar, which is the main menu for
an application.
o
The
standard menu, which can contain
either items to be selected or other
menus (submenus).
o
The
context menu, which is often
activated by right-clicking the mouse. Context menus are also called popup menus.
o
Several
different types of menu items,
including the ability to create custom
menu items.
o
Accelerator keys, which enable menu items to be selected without having
to activate the menu.
o
Mnemonics, which allow a menu item to be selected by the keyboard
once the menu options are displayed.
§ JavaFX also supports an interesting control
called MenuButton, which lets user
create a button that activates a menu.
§ JavaFX also supports the toolbar, which provides
rapid access to program functionality, often paralleling menu items.
Menu Basics
§ The JavaFX menu system is supported by a
group of related classes packaged in javafx.scene.control.
TABLE 8-1. The Core JavaFX Menu Classes
§ To provide a main menu for an application,
you need an instance of MenuBar.
This class is, a container for menus.
§ The MenuBar
contains instances of Menu.
§ Each Menu
object defines a menu. That is, each Menu
object contains one or more selectable items.
§ The items displayed by a Menu are objects of type MenuItem.
§ Thus, a MenuItem
defines a selection that can be chosen by the user.
§ check and radio menu items can be added to a menu.
o
A
check menu item is created by CheckMenuItem.
o
A
radio menu item is created by RadioMenuItem.
§ Both of these classes extend MenuItem.
§ SeparatorMenuItem is a convenience class that creates a
separator line in a menu. It inherits CustomMenuItem,
which is a class that facilitates embedding other types of controls in a menu
item. CustomMenuItem extends MenuItem.
§ When a menu item is selected, an action event is generated.
§ The name
of the selection is the text
associated with the selection.
§ NOTE:
1. MenuItem
does not inherit Node.
i. Thus, instances of MenuItem can be used only in a menu.
ii. They cannot be otherwise incorporated into a
scene graph.
2. MenuBar
does inherit Node
i. This allows the menu bar to be added to the
scene graph.
3. MenuItem
is a superclass of Menu.
i. This enables the creation of submenus – menus
within menus.
ii. To create a submenu,
1. first create and populate a Menu object with MenuItems
2. and then add it to another Menu object.
§
ContextMenu inherits PopupControl.
§ To create a context menu,
§ first create an object of type ContextMenu.
§ Then, add MenuItems to it.
§ A context menu is often activated by clicking
the right mouse button when the mouse is
over a control for which a context menu has been defined.
§ Another way to create a stand-alone menu is
to use the MenuButton or SplitMenuButton controls.
§ MenuButton
displays a button control
that is used to activate a drop-down menu.
§ SplitMenuButton
displays both a button and a
menu activator box, which is used to activate a drop-down menu.
§ Both controls are quite useful when screen
space is limited.
§ A feature related to the menu is the toolbar.
§ In JavaFX, toolbars are supported by the ToolBar class.
§ It creates a stand-alone component that is
often used to provide fast access to functionality contained within the menus
of the application.
An Overview of MenuBar, Menu, and MenuItem
§ To create a menu, need MenuBar, Menu, and MenuItem.
MenuBar
§ MenuBar
is essentially a container
for menus.
§ It is the control that supplies the main menu
of an application.
§ It inherits Node and can be added to a scene graph.
§ MenuBar
has two constructors.
o
The
first is the default constructor.
o
The
second constructor – can specify the items in the menu.
§ As a general rule, an application has one and
only one menu bar.
§ MenuBar
defines several methods,
§ getMenus(
) – It returns a list of the
menus managed by the menu bar.
final
ObservableList<Menu> getMenus( )
§ A Menu
instance is added to this list of menus by calling add( ) or addAll( ).
§ The added menus are positioned
in the order in which they are added.
§ To remove a menu that is no longer needed,
call remove( ).
§ To obtain a count of the number of items in a
menu bar, call size( ).
Menu
§ Menu
encapsulates a menu, which
is populated with MenuItems.
§ Menu is derived from MenuItem.
§ one menu can be a submenu of another.
§ Menu
defines several
constructors.
o Default
o Menu(String name)
§ Each menu maintains a list of menu items that
it contains.
§ After a menu has been constructed, you can
add an item to the menu by adding items to this list using getItems( ) and add( ) or
addAll( ).
final
ObservableList<MenuItem> getItems( )
§ to remove an item call remove( )
§ to obtain the size of the list call size( ).
§ Separators help organize long menus by
allowing you to group related items together. To add a menu separator use an
object of type SeparatorMenuItem.
MenuItem
§
MenuItem encapsulates an element in a menu.
§ This element can either be a selection linked
to some program action, such as Save or Close, or it can cause a submenu to be
displayed.
§ MenuItem
defines the following three
constructors:
o
MenuItem(
)
o
MenuItem(String
name)
o
MenuItem(String
name, Node image)
§ A MenuItem
generates an action event when selected. You can register an action event
handler for such an event by calling setOnAction(
), or fire an action event on a menu item by calling fire( ).
§ MenuItem
– methods.
§ setDisable(
) – enable or disable a menu
item.
final
void setDisable(boolean disable)
Create a Main Menu
§ As a general rule, the most commonly used
menu of any application is the main menu.
This is the menu defined by the menu bar, and it is the menu that defines all
(or nearly all) of the functionality of the program. As you will see, JavaFX
streamlines the process of creating and managing the main menu. Here, you will
learn how to construct a simple main menu. Subsequent sections will show
various options.
§ Constructing the main menu requires several
steps. Here is one approach. First, create the MenuBar instance that will hold the menus. Next, construct each
menu that will be in the menu bar. In general, a menu is constructed by first
creating a Menu object and then
adding MenuItems to it. After the
menus have been created, add them to the menu bar. Then, the menu bar itself
must be added to the scene graph. Finally, for each menu item, you must add an
action event handler that responds to the action event fired when a menu item
is selected.
§ NOTE
§ If you are using a
recent version of JavaFX 8 (one that incorporates update 40), then you can also
add menu items when you construct the menu and specify the menus when you
construct the menu bar, although this approach may not be applicable to all
situations. This book will use the traditional approach.
§ A good way to understand the process of
creating and managing menus is to work through an example.
§ Here is a program that creates a simple menu
bar that contains three menus. The first is a standard File menu that contains
Open, Close, Save, and Exit selections. The second menu is called Options, and
it contains two submenus called Input Devices and Clock Style, and a Reset
entry. The third menu is called Help, and it has one item: About. When a menu
item is selected, the name of the selection is displayed in a label.
§
Let’s
examine in detail how the menus in this program are created, beginning with the
MenuDemo constructor. Note that it
uses a BorderPane instance for the
root node. As explained in Chapter 5,
it defines a layout that has five areas: top, bottom, left, right, and center.
Later in the program, the menu bar is positioned in the top location and a
label that displays the menu selection is set to the center position. Setting
the menu bar to the top position ensures that it will be shown at the top of
the application and will automatically be resized to fit the horizontal width
of the window. This is why BorderPane is
used in the menu examples. Of course, other layouts, such as using a VBox, are also valid.
§ Much of the code in the program is used to
construct the menu bar, its menus, and menu items, and this code warrants a
close inspection. First, the menu bar is constructed and a reference to it is
assigned to mb by this statement:
Add Mnemonics and Accelerators to Menu Items
§ The menu created in the preceding example is
functional, but it is possible to make it better. In real applications, a menu
usually includes support for keyboard shortcuts. These come in two forms:
accelerators and mnemonics. An accelerator
is a key combination that lets you select a menu item without having to
first activate the menu. As it applies to menus, a mnemonic defines a key that lets you select an item from an active
menu by typing the key. Thus, a mnemonic allows you to use the keyboard to
select an item from a menu that is already being displayed.
§ An accelerator can be associated with a
Menu or MenuItem. It is specified by calling setAccelerator( ), shown next:
§ final void setAccelerator(KeyCombination keyComb)
§ Here, keyComb is the key combination that is pressed to select the menu
item. KeyCombination is a class that
encapsulates a key combination, such as CTRL-s. It is packaged in javafx.scene.input.
§ KeyCombination defines two protected constructors, but often you will use the keyCombination( )
§ factory method, shown here:
§ static KeyCombination keyCombination(String keys)
§ Here, keys
is a string that specifies the key combination. It typically consists of a
modifier, such as CTRL, ALT, or SHIFT, and a letter, such as S. There is a
special value, called shortcut,
which can be used to specify the control key in a Windows system and the meta
key on a Mac. (It also maps to the typically used shortcut key on other types
of systems.) Therefore, if you want to specify CTRL-S as the key combination
for Save, then use the string “shortcut+S”. This way, it will work for both
Windows and Mac, and elsewhere.
§
The
following sequence adds accelerators to the File menu created by the MenuDemo program in the previous
section. After making this change, you can directly select a File menu option
by pressing CTRL-O, CTRL-C, CTRL-S, or CTRL-E.
§ You will also need to import javafx.scene.input.*;.
§ A mnemonic can be specified for both MenuItem and Menu objects, and it is easy to do. Simply precede the letter in
the name of the menu or menu item with an underscore. For example, in the
preceding example, to add the mnemonic F to
the File menu, declare fileMenu as
shown here:
§ After making this change, you can select the
File menu by pressing ALT and then F. However, mnemonics will be active only if
mnemonic parsing is enabled (as it is by default). You can turn mnemonic
parsing on or off by using setMnemonicParsing(
), shown here: final void setMnemonicParsing(boolean enable)
§ Here, if enable
is true, then mnemonic parsing
is turned on. Otherwise, it is turned off.
§ After making these changes, the File menu
will now look like this:
Use RadioMenuItem and CheckMenuItem
§ In addition to the standard type of menu
items just shown, JavaFX defines two others: check menu items and radio menu
items. These elements can streamline a GUI by allowing a menu to provide
functionality that would otherwise require additional stand-alone components.
Also, sometimes check or radio menu items simply seem the
most natural way to include a specific set of options. Whatever your reason, it
is easy to use check and/or radio menu items in menus, and both are examined
here.
§ To add a check menu item to a menu, use Check MenuItem. It defines three
constructors, which parallel the ones defined by MenuItem. The one used in this chapter is shown here:
§ CheckMenuItem(String name)
§ Here, name
specifies the name of the item. The initial state of the check box is
unchecked. If you want to check a check menu item under program control, call setSelected( ), shown here:
§ final void setSelected(boolean selected)
§ If selected
is true, the menu item is
checked. Otherwise, it is unchecked.
§ Like stand-alone check boxes, check menu
items generate action events when their state is changed.
§ Check menu items are especially appropriate
in menus when you have options that can be selected and you want to display
their selected/deselected status.
§ A radio menu item can be added to a menu by
creating an object of type RadioMenuItem.
§ RadioMenuItem
defines a number of
constructors. The one used in this chapter is shown here: RadioMenuItem(String name)
§ It creates a radio menu item that has the
name passed in name. The item is not
selected. As with the case of
§ check menu items, to select a radio menu
item, call setSelected( ), passing true as an argument.
§ RadioMenuItem
works like a stand-alone
radio button, generating both change and action events. Like stand-alone radio
buttons, radio menu items must be put into a toggle group in order for them to
exhibit mutually exclusive selection behavior.
§ Because both Check MenuItem and RadioMenuItem
inherit MenuItem, each has all
of the functionality provided by MenuItem.
Aside from having the extra capabilities of check boxes and radio buttons, they
act like and are used like other menu items.
§ To try check and radio menu items, first
remove the code that creates the Options menu in the MenuDemo example program. Then substitute the following code
sequence, which uses check menu items for the Input Devices submenu and radio
menu items for the Clock Style submenu:
§
Although
the two types of menu items look similar, they behave differently. With radio
menu items, you can select only one at a time. With check menu items, you can
select zero or more items.
Context Menu (pop-up menu)
§ A popular alternative or supplement to the
menu bar is the popup menu, which in JavaFX is referred to as a context menu.
§ Popup menus are supported in JavaFX by the ContextMenu class
§ ContextMenu
has two constructors.
Default
constructor
ContextMenu(MenuItems
… menuItems )
menuItems specify the menu items that
will constitute the context menu.
Associate
and activate ContextMenu
§ Context menu is activated by clicking the right mouse button when over a control.
§ associate a context menu with a control using
setContextMenu( ) on the control
final
void setContextMenu(ContextMenu menu)
menu specifies the context menu associated with the invoking
control.
Steps.
1. Creating ContextMenu
2. Create MenuItems
3. Use getItems and add MenuItems to ContextMenu
4. Associate ContextMenu with a control using setContextMenu()
5. Add appropriate EventHandlers to MenuItems
6. Add ContextMenu to layout and place in scene
MenuButton
§ The menu button offers a compact way to add a
menu to a layout because it will show only when needed.
§ It provides a mechanism that links a push
button with a drop-down menu.
§ Only the button is shown, but when it is
pressed, a menu drops down.
§ Menu buttons are supported by the MenuButton class.
§ MenuButton
defines several
constructors.
Default
and MenuButton(String str)
Here,
str is the text shown in the button.
Steps.
1. Creating MenuButton
2. Create MenuItems
3. Use getItems and add MenuItems to MenuButton
4. Add appropriate EventHandlers to MenuItems
5. Add MenuButton to layout and place in scene.
// JavaFX Controls
// Menu
import javafx.application.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.event.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.scene.control.ScrollPane.*;
import javafx.scene.input.*;
import javafx.scene.text.*;
import javafx.geometry.*;
public class Menu_Demo extends Application
{
public
static void main(String []as)
{
launch(as);
}
public
void init(){}
public
void stop(){}
public
void start(Stage myStage)
{
myStage.setTitle("JavaFX
- Menu");
BorderPane
bp = new BorderPane();
Label
L1 = new Label();
L1.setWrapText(true);
L1.setTextAlignment(TextAlignment.JUSTIFY);
L1.setMaxWidth(150);
//
create menubar
MenuBar
mb = new MenuBar();
//
create menu
Menu
Filemenu = new Menu("_File");
Menu
Editmenu = new Menu("_Edit");
Menu
Helpmenu = new Menu("_Help");
//
create menuitems - File
MenuItem
open = new MenuItem("Open");
MenuItem
save = new MenuItem("Save");
MenuItem
close = new MenuItem("Close");
MenuItem
exit = new MenuItem("Exit");
//
create menuitems - Edit
MenuItem
cut = new MenuItem("Cut");
MenuItem
copy = new MenuItem("Copy");
MenuItem
paste = new MenuItem("Paste");
//
create menuitems - Help
MenuItem
help = new MenuItem("Help");
MenuItem
about = new MenuItem("About");
//
add menuitems to menu
Filemenu.getItems().addAll(open,
save, close, new SeparatorMenuItem(), exit);
Editmenu.getItems().addAll(cut,
copy, paste);
Helpmenu.getItems().addAll(help,
new SeparatorMenuItem(), about);
//
add menu to menu bar
mb.getMenus().addAll(Filemenu,Editmenu);
mb.getMenus().add(Helpmenu);
//
place menubar in scene using border layout
bp.setTop(mb);
bp.setCenter(L1);
//
Event handling
about.setOnAction(new
EventHandler<ActionEvent>()
{
public
void handle(ActionEvent ae)
{
L1.setText("This
is a demo program for JavaFX Menu and event handling.");
}
});
exit.setOnAction(new
EventHandler<ActionEvent>()
{
public
void handle(ActionEvent ae)
{
Platform.exit();
}
});
//
Add keyboard accelerators
open.setAccelerator(KeyCombination.keyCombination("shortcut+O"));
save.setAccelerator(KeyCombination.keyCombination("shortcut+S"));
close.setAccelerator(KeyCombination.keyCombination("shortcut+C"));
exit.setAccelerator(KeyCombination.keyCombination("shortcut+X"));
help.setAccelerator(KeyCombination.keyCombination("shortcut+H"));
about.setAccelerator(KeyCombination.keyCombination("shortcut+A"));
//
Context Menu
ContextMenu
cm = new ContextMenu();
MenuItem
clear = new MenuItem("Clear");
MenuItem restore = new MenuItem("Restore");
cm.getItems().addAll(clear,
restore);
L1.setContextMenu(cm);
clear.setOnAction(new
EventHandler<ActionEvent>()
{
public
void handle(ActionEvent ae)
{
L1.setText("");
}
});
restore.setOnAction(new
EventHandler<ActionEvent>()
{
public
void handle(ActionEvent ae)
{
L1.setText("This
is a demo program for JavaFX Menu and event handling.");
}
});
//
Submenus
//
Radiobuttons in menus
Menu
gender = new Menu("Gender");
RadioMenuItem
male = new RadioMenuItem("Male");
RadioMenuItem
female = new RadioMenuItem("Female");
ToggleGroup
tg = new ToggleGroup();
male.setToggleGroup(tg);
female.setToggleGroup(tg);
male.setSelected(true);
gender.getItems().addAll(male,female);
//
Submenus
//
Checkboxes in menus
Menu
dept = new Menu("Dept");
CheckMenuItem
it = new CheckMenuItem("IT");
CheckMenuItem
cse = new CheckMenuItem("CSE");
CheckMenuItem
others = new CheckMenuItem("Others");
dept.getItems().addAll(it,cse,new
SeparatorMenuItem(), others);
//
add the two menus to main menu
Menu
btn = new Menu("_Button");
btn.getItems().addAll(gender,dept);
//
add menus to menubar
mb.getMenus().add(btn);
//
Menu button
MenuButton
mbtn = new MenuButton("Footer");
MenuItem
status = new MenuItem("Status");
MenuItem
hitcount = new MenuItem("Hit count");
mbtn.getItems().addAll(status,hitcount);
Label
L2 = new Label();
HBox
hb = new HBox(10);
hb.getChildren().addAll(mbtn,
L2);
bp.setBottom(hb);
status.setOnAction(new
EventHandler<ActionEvent>()
{
public
void handle(ActionEvent ae)
{
L2.setText("JavaFX
Menu demonstrated!");
}
});
hitcount.setOnAction(new
EventHandler<ActionEvent>()
{
public
void handle(ActionEvent ae)
{
L2.setText("Hit
count = 232");
}
});
Scene
myScene = new Scene(bp, 300, 200);
myStage.setScene(myScene);
myStage.show();
}
}
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu