0% found this document useful (0 votes)
22 views65 pages

Chapter 1 AWT and SWING

This document provides an overview of advanced programming concepts in Java, including: 1) It describes the differences between AWT and Swing components, and introduces common Swing components like JButton and JTextField. 2) It explains the basics of Swing GUI programming, including components, containers, layout managers, and how to develop basic GUIs. 3) It provides details on common layout managers like FlowLayout, GridLayout, and BorderLayout and how to use them to position components.

Uploaded by

faayaoromoo14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views65 pages

Chapter 1 AWT and SWING

This document provides an overview of advanced programming concepts in Java, including: 1) It describes the differences between AWT and Swing components, and introduces common Swing components like JButton and JTextField. 2) It explains the basics of Swing GUI programming, including components, containers, layout managers, and how to develop basic GUIs. 3) It provides details on common layout managers like FlowLayout, GridLayout, and BorderLayout and how to use them to position components.

Uploaded by

faayaoromoo14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Advanced Programming

Chapter 1: AWT and Swings


Introduction
• Java provides two types of GUI components having
different natures.
– AWT Components
– Swing Components
• AWT Components
– The original user interface toolkit.
– Defined in java.awt package.
– Platform dependent.
– Does not support advanced components like Grids, Trees
& Tables.
– Classes like Button, TextField, ComboBox, …. are used

2
Introduction…
• Swing Components
– The new user interface toolkit.
– They are pure Java Components.
– Defined in javax.swing package
– Platform independent.
– Pre-fabricated components.
– Supports advanced components.
– Supports everything you need to build a user interface for
your Java application.
– Classes like JButton, JTextField, JComboBox, …. are
used

3
Basics of Swing GUI Programming
• Components
– A component is the fundamental user interface object in
Java.
– Everything you see on the display in a Java application is
a component.
• This includes things like windows, drawing canvases, buttons,
checkboxes, scrollbars, lists, menus, and text fields.
– To be used, a component usually must be placed in a
container.
– All Swing components are derived from the abstract
javax.swing.JComponent class.

4
5
Basics…
• We can split the functionality of the JComponent
class into two categories:
– Appearance and
– Behavior
• The JComponent class contains methods and
variables that control an object's general
appearance.
– This includes basic attributes such as its visibility, its
current size and location, and certain common graphical
defaults, like font and color.
– The JComponent class also contains methods
implemented by specific subclasses to produce the
graphical displays. 6
Basics…
• Component's behavior specify the way it responds
to user-driven events.
– When the user performs an action (like pressing the
mouse button) within a component's display area, a
Swing thread delivers an event object that describes
"what happened.“
– The event is delivered to objects that have registered
themselves as "listeners" for that type of event from that
component.
– Events are delivered by invoking designated event-
handler methods within the receiving object (the
"listener").

7
Basics…
• Containers
– A container is a component that holds and manages other
components.
– Container objects group components, arrange them for
display using a layout manager, and associate them with a
particular display device.
– JComponent objects can be containers, because the
JComponent class descends from the Container class.
– Three of the most useful container types are JFrame ,
JPanel, and JApplet.
• JFrame is derived from JWindow, which is pretty much the same
but lacks a border.

8
Basics…
• Containers…
• A JPanel is a generic container element used to group
components inside of JFrames and other JPanels.
• The JApplet class is a kind of container that provides the
foundation for applets that run inside web browsers.
• Layout Managers:
– A layout manager arranges the child components of a
container.
– It positions and sets the size of components within the
container's display area according to a particular layout
scheme.
– It fits the components into the available area while
maintaining the proper spatial relationships among the
components. 9
Basics…
• Layout managers…

– Every container has a default layout manager; You can


install a new layout manager at any time with the
setLayout() method.
– For example, we can set the layout manager of a
container to a BorderLayout:
• setLayout (new BorderLayout());
10
Basics…
• Layout Managers…
– Every component determines three important pieces of
information used by the layout manager in placing and
sizing it:
• a minimum size,
• a maximum size, and
• a preferred size.
– These sizes are reported by the getMinimumSize(),
getMaximumSize(), and getPreferredSize() methods of
Component, respectively.
• For example, a plain JButton object can normally be changed to
any size. However, the button's designer can provide a preferred
size for a good looking button.

11
Basics…
• FlowLayout:
– FlowLayout is a simple layout manager that tries to
arrange components with their preferred sizes, from left
to right and top to bottom in the container.
– A FlowLayout can have a specified row justification of
LEFT, CENTER, or RIGHT, and a fixed horizontal and
vertical padding.
– By default, a flow layout uses CENTER justification
– It is the default for JPanels.
– When it can’t fit more components in a row, it starts a
new row, similar to a word processor with word wrap
enabled.

12
Basics…
• FlowLayout…
– When the container is resized, the components within it
are repositioned based on the container’s new size.
– Components within a FlowLayout-managed container are
given their preferred size.

13
Basics…
• GridLayout
– The GridLayout manager lays out objects in rows and
columns, where each cell in the layout has the same size.
– Components are added to the layout from left to right,
top to bottom.
– The components are arbitrarily resized to fit the grid;
• their minimum and preferred sizes are consequently ignored.
– GridLayout takes the number of rows and columns in its
constructor.
– A call to setLayout(new GridLayout(3, 4)) changes the
layout manager of the current container to a GridLayout
with three rows and four columns

14
Basics…
• GridLayout…
– If you subsequently give it too many objects to manage, it
adds extra columns to make the objects fit.
– You can also set the number of rows or columns to zero,
which means that you don't care how many elements the
layout manager packs in that dimension.
• For example, GridLayout(2,0) requests a layout with two rows
and an unlimited number of columns;

15
Basics…
• BorderLayout
– BorderLayout is the default layout manager for JFrame,
JWindow, JDialog, JInternalFrame, and JApplet.
– It provides for a more flexible way of positioning
components along the edges of the window.
– When using BorderLayout, you add components with
constraints to identify in which of the five locations to
place the component.
– If you don’t specify a constraint, the component is added
to the center area.
• Adding multiple components to the same area shows only the last
component

16
Basics…
• BorderLayout…
– Because each component is associated with a direction,
– BorderLayout can manage at most five components.
– Constants of BorderLayout manager are: NORTH,
SOUTH, EAST, WEST, and CENTER.

17
Steps to Develop GUIs (Beginners)
• Import necessary packages. (eg. javax.swing)
• Define necessary classes and methods.
• Create instances of containers. (eg. Jframe, JPanel)
• Create instances of components. (eg. JButton)
• Define the appearance and Behavior properties of
components. (eg. Enable, Events)
• Install layout manager for the containers and add the
components to it appropriately.
• Define the appearance & behaviours of the container
object. (eg. visibility, location)

18
JToolTip Class
• The Swing components support the ability to display
brief pop-up messages when the cursor rests over them.
• The class used to display pop-up messages is JToolTip.
• Calling the public void setToolTipText(String text)
method automatically causes the creation of a JToolTip
instance when the mouse rests over a component with
the installed pop-up message.
• Tooltip text is normally one line long.

19
JToolTip…
• If the text string begins with <html> then the
contents can be any HTML 3.2 formatted text.
• Syntax to add tooltip text is
– component.setToolTipText(String text);
• Eg. userText.setToolTipText(“Enter your username here.”);

– component.setToolTipText("<html>Tooltip<br>Message"
)
• Eg. userText.setToolTipText(“<html>Username should start with
<br>small case and should contain @.”);

20
JLabel Class
• Serves as the replacement component for the AWT
Label but it can do much more.
– The AWT Label is limited to a single line of text, the Swing
JLabel can have text, images, or both.
• The text can be a single line of text or HTML.
• In addition JLabel can support different enabled and
disabled images.
• Creating a JLabel: There are six constructors for
JLabel:
– public JLabel()
• JLabel label = new JLabel();
– public JLabel(Icon image)
• Icon icon = new ImageIcon("dog.jpg");
21
• JLabel label = new JLabel(icon);
JLabel Class…
– public JLabel(Icon image, int horizontalAlignment)
• Icon icon = new ImageIcon("dog.jpg");
• JLabel label = new JLabel(icon, JLabel.RIGHT);
– public JLabel(String text)
• JLabel label = new JLabel("Dog");
– public JLabel(String text, int horizontalAlignment)
• JLabel label = new JLabel("Dog", JLabel.RIGHT);
– public JLabel(String text, Icon icon, int
horizontalAlignment)
• Icon icon = new ImageIcon("dog.jpg");
• JLabel label = new JLabel("Dog", icon, JLabel.RIGHT);

22
JLabel Class…
• JLabel properties
– Allow you to customize the content, position, and (in a
limited sense) the behavior of the JLabel.
Property Name DataType Access
– disabledIcon Icon Read-write bound
– displayedMnemonic char Read-write bound
– displayedMnemonicIndex int Read-write bound
– horizontalAlignment int Read-write bound
– horizontalTextPosition int Read-write bound

23
JLabel Class
• JLabel Event Handling:
– No event-handling capabilities are specific to the JLabel.
– The closest thing there is for event handling with the
JLabel is the combined usage of the displayedMnemonic,
displayedMnemonicIndex, and labelFor properties.
– When the displayedMnemonic and labelFor properties
are set, pressing the keystroke specified by the mnemonic,
along with the platform-specific hotkey (usually Alt),
causes the input focus to shift to the component
associated with the labelFor property.

24
JLabel Class…
• JLabel Event Handling…
– This can be helpful when a component doesn’t have its
own manner of displaying a mnemonic setting, such as
with all the text input components.
– Eg.
JLabel label = new JLabel("Username");
JTextField textField = new JTextField();
label.setDisplayedMnemonic(KeyEvent.VK_U);
label.setLabelFor(textField);

25
AbstractButton Class
• An important Swing class that works behind the
scenes as the parent class of all the Swing button
components.
• The JButton is the simplest of the subclasses.
• Each of the AbstractButton subclasses uses the
ButtonModel interface to store their data model.
• Any set of AbstractButton objects can be grouped
into a ButtonGroup.
– Although this grouping is most natural with the
JRadioButton and JRadioButtonMenuItem components

26
JButton Class
• The basic AbstractButton component that can be
selected.
• It supports text, images, and HTML-based labels.

27
JButton Class…
• Creating JButton: JButton can be created with one
of its constructors:
– public JButton()
• JButton button = new JButton();
– public JButton(Icon image)
• Icon icon = new ImageIcon("dog.jpg");
• JButton button = new JButton(icon);
– public JButton(String text)
• JButton button = new JButton("Dog");
– public JButton(String text, Icon icon)
• Icon icon = new ImageIcon("dog.jpg");
• JButton button = new JButton("Dog", icon);

28
JButton Class…
• Handling JButton Events:
– The JButton component itself has no specific event-
handling capabilities.
• They’re all inherited from AbstractButton.
– The most helpful listener with the JButton is the
ActionListener.
– When the JButton component is selected, all registered
ActionListener objects are notified.
– When the button is selected, an ActionEvent is passed to
each listener.
• This event passes along the actionCommand property of the
button to help identify which button was selected when a shared
listener is used across multiple components.
29
JButton Class…
• Handling JButton Events….
– If the actionCommand property hasn’t been explicitly set,
the current text property is passed along instead.
• The explicit use of the actionCommand property is helpful with
localization.

30
JButton Class…
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonEvent extends JFrame{
public static void main(String args[]){
final JFrame frame = new JFrame("Button event");
}
//Declares two button objects
JButton okButton = new JButton("Ok");
JButton cancelButton = new JButton("Cancel");
//Declares the listener for the button
//Define action to happen when the user clicks the buttons
ActionListener actionListener = new ActionListener(){
public void actionPerformed(ActionEvent event){
String command = event.getActionCommand();
JOptionPane.showMessageDialog(frame,"Youclicked:"+command+" button");
}};
//Registers the above declared listener for both buttons
okButton.addActionListener(actionListener);
cancelButton.addActionListener(actionListener);
frame.setLayout(new GridLayout(1,2,10,10));
frame.add(okButton);
frame.add(cancelButton);
frame.setSize(300,200);
frame.setVisible(true);
frame.setResizable(false);
//Enforce the frame not to be resized
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 31
}
JTextField Class
• Is the text component for a single line of input.
• The data model for a JTextField is the
PlainDocument implementation of the Document
interface.
• The PlainDocument model limits input to single-
attributed text, meaning that it must be a single font
and color.
• When the Enter key is pressed within the JTextField,
it automatically notifies any registered
ActionListener implementations.

32
JTextField Class…
• Creating a JTextField: JTextField can be created
with one of its constructors.
– public JTextField()
• JTextField textField = new JTextField();
– public JTextField(String text)
• JTextField textField = new JTextField("Initial Text");
– public JTextField(int columnWidth)
• JTextField textField = new JTextField(14);
– public JTextField(String text, int columnWidth)
• JTextField textField = new JTextField("Initial Text", 14);
– public JTextField(Document model, String text, int
columnWidth)
• JTextField textField = new JTextField(aModel, null, 14);
33
JTextField Class…
• JTextField Properties:
– setEditable(boolean bool): used to change the editability
of a textfield object.
• This means if bool is true then user can write into a textfield and
edit its content.
• But if bool is false then user cannot edit the content of a textfield
object.
• Eg. userText.setEditable(false);
– actionCommand: is associated with the content of a
textfield object. i.e what is written in the textfield.
• It is implemented using two kinds of methods:
setActionCommand(String) and getActionCommand().

34
JTextField Class…
• JTextField Properties….
– actionListeners: is used to declare and define listeners for
textfield objects.
• Actions for a textfield happens when the user types in the
textfield and press enter key.
• Like Button object, textfield actionListeners listens and take
actions by implementing actionPerformed method as shown in
the following code fragement.
Syntax: ActionListener actionListener = new ActionListener(){
public void actionPerformed(ActionEvent event){
//the code goes here.
}
}

35
JTextField Class…
• JTextField Properties…
– setHorizontalAlignment(int): used to adjust the position
of the text in the textfield object.
• The int has three types of values: JTextField.LEFT,
JTextField.CENTER, JTextField.RIGHT.

Syntax: textField.setHorizontalAlignment(JTextField.RIGHT);

36
JComboBox Class
• The Swing component set is a multiple-part
component.
• Allows a user to choose from a predefined set of
choices with the help of a pull-down list.
• A JComboBox acts like a JLabel to display the
current user selection.
• Embedded within the JLabel is a pop-up menu
containing choices within a JList control.
• When the desired choice isn’t available, the
JComboBox can use a JTextField to enter a new
choice.
37
JComboBox Class…
• The text field for editing is disabled by default,
permitting a user to select from the set of predefined
choices only.
• The JList part is automatically embedded within a
JScrollPane when desired;
• You don’t need to manually create the JList or place
it in the JScrollPane.

Advanced Programming 38
JComboBox Class…
• Four essential elements define the JComboBox
component and its implementation:
– A data model for holding the JComboBox data, as defined
by the ListModel interface.
– A cell renderer for drawing the elements of the
JComboBox, as described by the ListCellRenderer
interface
– An editor for entering choices not part of the predefined
data model, as defined by the ComboBoxEditor interface
– A keystroke manager for handling keyboard input to
select elements of the JComboBox, as described by the
KeySelectionManager interface
• Many of the JComboBox capabilities are shared
39
with the JList component.
Creating JComboBox Components
– public JComboBox()
• JComboBox emp = new JComboBox();
– Creates an empty list JComboBox instance.
– public JComboBox(Object listData[])
• String cities[] ={"Adama","Asosa","Bahirdar",“Addis Ababa",
“Gambella","Harar","Hawassa","Jigjiga",
"Mekelle","Samara"};
• JComboBox cityCombo = new JComboBox(cities);
– Creates a combo box with list of choices.

40
JComboBox Properties
• After you create a JComboBox component, you can
modify each of its many properties.
– maximumRowCount: This property allows you to control
the maximum number of visible entries in the pop-up list.
• Syntax: comboBoxObject.setMaximumRowCount(int);
• Eg. cityCombo.setMaximumRowCount(5);
– selectedItem: This property deals with the currently
selected item.
• both getter and setter methods with the former helping you to
read and the later helping you to set a new item to the combo box.
– Syntax: comboBoxObject.setSelectedItem(String );
– Syntax: comboBoxObject.getSelectedItem();

41
JComboBox Properties…
• Eg1. cityCombo.setSelectedItem(“Samara”);
– //The item ‘Samara’ will selected and displayed.
• Eg2. cityCombo.getSelectedItem();
– //Returns the currently selected Item.
– selectedIndex: items can also be accessed based on
the assigned index to them. Two methods exist:
setSelectedIndex(int) and getSelectedIndex().
• Eg1. cityCombo.setSelectedIndex(6);
– //Selects the item with an index value 6. i.e. ‘Hawassa’
• Eg2. cityCombo.getSelectedIndex();
– //Returns the index value of the currently selected item.
– itemCount: Counts the total number of items that
the current combo box object has.
• Syntax: comboBoxObject.getItemCount();
– Eg. comboBox.getItemCount(); 42
Handling JComboBox Events
• JComboBox’s component will fire up an event
when:
– An item is selected or
– A text is entered from keyboard
• JComboBox component supports at least three
different events related to selection.
– One can Listen for keyboard input to support key
selection with the help of the JComboBox’s
KeySelectionManager class.
– You can also listen with an ActionListener or an
ItemListener to find out when the selected item of the
JComboBox changes.
43
Listening to Keyboard Events with a
KeySelectionManager
• The default manager locates the next element that corresponds to
the pressed key.
• It has memory, so if you have entries that start with similar
prefixes, users can continue typing until there is enough of a
match to be unique.
• NB: The KeySelectionManager works only in combo boxes that
are not editable.

– If you need to turn off a key selection manager, simply type the
following code.
JComboBox.KeySelectionManager manager =
new JComboBox.KeySelectionManager() {
public int selectionForKey(char aKey, ComboBoxModel aModel) {
return -1;
}
};
44
cityCombo.setKeySelectionManager(manager);
Listening to JComboBox Events with an
ActionListener
• Will tell you when an element has been selected
within a JComboBox.
• The listener doesn’t know which element is selected.
• It must ask the JComboBox that served as the
source of the event.
• To determine the selected element from the
JComboBox, use either getSelectedItem() or
getSelectedIndex().

45
Swing Menus & ToolBars
• Menus and toolbars help make your applications
more user-friendly by providing visual command
options.
• Although Swing menus do support multiple-key
command sequences, the menus (and toolbars) are
designed primarily for on-screen graphical selection
with a mouse, rather than the keyboard.

46
Swing Menus & ToolBars

47
Swing Menus…
• Here is the general way you have to do when you work
with JMenu:
– For each cascading menu, you create a JMenu
component and add it to the JMenuBar.
– For the selections available from the JMenu, you
create JMenuItem components and add them to the
JMenu.
– To create submenus, you add a new JMenu to a
JMenu and place JMenuItem options on the new
menu.
– Then, when a JMenu is selected, the system displays
its current set of components within a JPopupMenu.
48
JMenuBar Class
• Swing’s menu bar component is the JMenuBar.
• Its operation requires you to fill the menu bar with
JMenu elements that have JMenuItem elements.
• Then you add the menu bar to a JFrame or some
other user interface component requiring a menu bar.
Creating JMenuBar components
• JMenuBar has a single constructor of the no-
argument variety: public JMenuBar().
• Once you create the menu bar, you can add it to a
window with the setJMenuBar() method of JApplet,
JDialog, JFrame, JInternalFrame, or JRootPane.
49
JMenuBar Class…
JMenuBar menuBar = new JMenuBar();
// Add items to it
...
JFrame frame = new JFrame("MenuSample Example");
frame.setJMenuBar(menuBar);
• With the system-provided look and feel types, the menu
bar appears at the top of the window, below any
window title (if present), with setJMenuBar().
• You can also use the add() method of a Container to add
a JMenuBar to a window. When added with the add()
method, a JMenuBar is arranged by the layout
manager of the Container.

50
Adding Menus to and Removing Menus from
Menu Bars
• You need to add JMenu objects to a JMenuBar.
• Otherwise, the only thing displayed is the border
with nothing in it. There’s a single method for
adding menus to a JMenuBar:
• public JMenu add(JMenu menu)
• The following lines add two JMenu components into
the menu bar.
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenu editMenu = new JMenu("Edit");
menuBar.add(editMenu);

51
Adding Menus…
• By default, consecutively added menus are displayed
from left to right.
• This makes the first menu added the leftmost menu and
the last menu added the rightmost menu.
• Menus added in between are displayed in the order in
which they’re added.
• In addition to the add() method from JMenuBar, several
overloaded varieties of the add() method inherited from
Container offer more control over menu positioning.
• Of particular interest is the add(Component
component, int index) method, which allows you to
specify the position in which the new JMenu is to appear.
• menuBar.add(fileMenu, 0); 52
Removing Menus…
• If you’ve added a JMenu component to a
JMenuBar, you can remove it with either the
remove(Component component) or remove(int
index) method inherited from Container this way:
• menubar.remove(edit);
• menubar.remove(0);

53
JMenuItem Class
• The JMenuItem component is the predefined
component that a user selects on a menu bar.
• As a subclass of AbstractButton, JMenuItem acts
as a specialized button component that behaves
similarly to a JButton.
Creating JMenuItem Component
– public JMenuItem()
• JMenuItem jMenuItem = new JMenuItem();
– public JMenuItem(Icon icon)
• Icon atIcon = new ImageIcon("at.gif");
• JMenuItem jMenuItem = new JMenuItem(atIcon);

54
Creating JMenuItem…
– public JMenuItem(String text)
• JMenuItem jMenuItem = new JMenuItem("Cut");
– public JMenuItem(String text, Icon icon)
• Icon atIcon = new ImageIcon("at.gif");
• JMenuItem jMenuItem = new JMenuItem("Options", atIcon);
– public JMenuItem(String text, int mnemonic)
• JMenuItem jMenuItem = new JMenuItem("Cut", KeyEvent.VK_T);
• The mnemonic allows you to select the menu through
keyboard navigation.
• For instance, you can simply press Alt-C on a Windows
platform to select the Cut menu item if the item appears on
an Edit menu that is already open.
• Letters are specified by the different key constants within
the java.awt.event.KeyEvent class.
55
JMenuItem Properties
• accelerator: This property allows you to add a
functionality that can help you use the menu item
from your keyboard.
– It uses a KeyStroke factory class that lets you create
instances based on key and modifier combinations.
– Here is how you can use this property:-
• First create an instance of KeyStroke class and use the
setAccelarator(KeyStroke) method to set up an accelerator for the
menu item.
• The following code fragment adds an accelerator (Ctrl – X) key for
the menu item called cutMenuItem.
KeyStroke cutMenuItemStroke = KeyStroke.getKeyStroke("control X");
cutMenuItem.setAccelerator(cutMenuItemStroke);

56
Handling JMenuItem Events
• The component inherits the ability to allow you to
listen for the firing of ChangeEvent and
ActionEvent through the ChangeListener and
ActionListener registration methods of
AbstractButton.
• In addition, the JMenuItem component supports
registering MenuKeyListener and
MenuDragMouseListener objects when
MenuKeyEvent and MenuDragMouseEvent events
happen.

57
Listening to JMenuItem Events with
ChangeListener
• With JMenuItem component the changes with
regard to arming, pressing, and selecting are the
same as with a JButton.
• A JMenuItem is armed when the mouse passes over
the menu choice and it becomes selected.
• A JMenuItem is pressed when the user releases the
mouse button over it.
• The button model for a plain JMenuItem never
reports being selected.
• If you move the mouse to another menu item
without selecting, the first menu item automatically
becomes unarmed. 58
Listening to JMenuItem Events
withActionListener
• The better listener to attach to a JMenuItem is the
ActionListener.
• It allows you to find out when a menu item is selected.
• Any registered ActionListener objects would be
notified when a user releases the mouse button over a
JMenuItem that is part of an open menu.
• Registered listeners are also notified if the user
employs the keyboard (whether with arrow keys or
mnemonics) or presses the menu item’s keyboard
accelerator to make a selection.
• You must add an ActionListener to every
JMenuItem for which you want an action to happen
59
when selected.
Listening to JMenuItem Events with a
MenuKeyListener
• JMenuItem objects also fire events when users
interact with them by typing a key on the keyboard.
• If you want to perform a task when an event occurs
on a JMenuItem object, you need to add a
MenuKeyListener to that JMenuItem object.
• To do this, you need know these Swing classes,
interfaces and methods:
– menuKeyTyped(MenuKeyEvent) - Event handler method
called when a key is typed on a menu item button. You
need to implement this method to perform your own task.

60
Listening to JMenuItem…
– menuKeyPressed(MenuKeyEvent) - Event handler
method called when a key is pressed on a menu item
button. You need to implement this method to perform
your own task.
– menuKeyReleased(MenuKeyEvent) - Event handler
method called when a key is released on a menu item
button. You need to implement this method to perform
your own task.
• MenuKeyEvent - A Swing class that represents an
event occurred on a menu item. The most important
method in this class is:

61
Listening to JMenuItem…
– getSource(): Method returns the object where the event
occurred. Not very useful.
– getKeyChar(): Method returns the character represented
by the key that triggered event.
– getKeyCode(): Method returns the code value
represented by the key that triggered event.
– getKeyText(): Method returns the text name of a given
key code value.
– getPath(): Method returns a list of menu objects
representing a path in the menu tree.
• The last object is the JMenuItem object that fired
the event.
62
JMenu Class
• The JMenu component is the basic menu item
container that is placed on a JMenuBar.
• When a JMenu is selected, the menu displays the
contained menu items within a JPopupMenu.
Creating JMenu Components
• The following two constructors for JMenu allow
you to create the component.
– public JMenu()
• JMenu jMenu = new JMenu();
– public JMenu(String label)
• JMenu jMenu = new JMenu("File");

63
Adding Menu Items to a JMenu
• Once you have a JMenu, you need to add
JMenuItem objects to it; otherwise, the menu will
not display any choices.
• Here are two ways to do so:
– jMenuObject.add(jMenuItemObject);
– jMenuObject.add(String label);
• When there are more than two JMenuItems, it is
observed when menu items that are different in
their functionality are separated using a line.
• Such things are done using JMenu’s
addSeparator() method.
64
Adding Menu Items…
• You have to add a separator to JMenu after adding
a JMenuItem object to the JMenu object which you
require the separator has come after.
• For instance the following code fragment displays a
separator between save and print menu items in file
menu.
JMenu fileMenu = new JMenu(“File”);
JMenuItem saveMenuItem = new JMenuItem(“Save”);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
JMenuItem printMenuItem = new JMenuItem(“Print”);
fileMenu.add(printMenuItem);

65

You might also like