0% found this document useful (0 votes)
24 views57 pages

Java Swing Menus and Components

This document discusses Java Swing components for menus and dialog windows. It provides examples for creating menus with JMenuBar, JMenu, and JMenuItem. It describes adding menus, submenus, and menu items. It also covers adding mnemonics and accelerators to menu items to allow keyboard selection of items. The document is an instruction guide, as parts of the code are presented and explained line-by-line.

Uploaded by

Vân Trần
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views57 pages

Java Swing Menus and Components

This document discusses Java Swing components for menus and dialog windows. It provides examples for creating menus with JMenuBar, JMenu, and JMenuItem. It describes adding menus, submenus, and menu items. It also covers adding mnemonics and accelerators to menu items to allow keyboard selection of items. The document is an instruction guide, as parts of the code are presented and explained line-by-line.

Uploaded by

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

JAVA PROGRAMMING

Week 7: Swing (part 2)


Lecturer: NGUYỄN Thị Minh Tuyền
Plan 2
1. Menu
2. Dialog window
3. Other components: JFileChooser,
JColorChooser

Java Programing
Plan 3
1. Menu
2. Dialog window
3. Other components: JFileChooser,
JColorChooser

Java Programing
Core Menu classes 4

Java Programing
JMenuBar, JMenu, and
JMenuItem 5
• These form the minimum set of classes needed to
construct a main menu for an application.
• JMenu and JMenuItem are also used by popup menus
à the foundation of the menu system.

Java Programing
JMenuBar [1] 6
• Is essentially a container for menus.
• Inherits JComponent
• Has only one constructor: default constructor.
àInitially the menu bar will be empty
àYou need to populate it with menus prior to use.
à Each application has one and only one menu bar.
• Methods:
• JMenu add(JMenu menu)
• Component add(Component menu, int idx)
• void remove(Component menu)
• void remove(int idx)

Java Programing
JMenuBar [2] 7
• Methods (cont.)
• int getMenuCount()
• MenuElement[] getSubElements()
• boolean isSelected()
• void setJMenuBar(JMenuBar mb)

Java Programing
JMenu [1] 8
• JMenu encapsulates a menu, which is populated with
JMenuItems.
• It is derived from JMenuItem à one JMenu can be a
selection in another JMenu à one menu to be a
submenu of another.
• Constructors:
• JMenu(String name)
• JMenu()
• Methods
• JMenuItem add(JMenuItem item)
• Component add(Component item, int idx)
• void addSeparator()

Java Programing
JMenu [2] 9
• Methods
• void insertSeparator(int idx)
• void remove(JMenuItem menu)
• void remove(int idx)
• int getMenuComponentCount()
• Component[ ] getMenuComponents()

Java Programing
JMenuItem 10
• JMenuItem encapsulates an element in a menu.
• JMenuItem is derived from AbstractButton, and
every item in a menu can be thought of as a special kind
of button à when a menu item is selected, an action
event is generated.
• Constructors:
• JMenuItem(String name)
• JMenuItem(Icon image)
• JMenuItem(String name, Icon image)
• JMenuItem(String name, int mnem)
• JMenuItem(Action action)
• Methods
• void setEnabled(boolean enable)

Java Programing
Example: Creation of main menu 11

Java Programing
1. //Demonstrate a simple main menu.
2.
3.
import java.awt.*;
import java.awt.event.*;
12
4. import javax.swing.*;
5. class MenuDemo implements ActionListener {
6. JLabel jlab;
7. MenuDemo() {
8. // Create a new JFrame container.
9. JFrame jfrm = new JFrame("Menu Demo");
10. // Specify FlowLayout for the layout manager.
11. jfrm.setLayout(new FlowLayout());
12. // Give the frame an initial size.
13. jfrm.setSize(220, 200);
14. //Terminate the program when the user closes the
15. application.
16. jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. // Create a label that will display the menu selection.
18. jlab = new JLabel();
19. // Create the menu bar.
Java Programing
20. JMenuBar jmb = new JMenuBar();
13
1. // Create the File menu.
2. JMenu jmFile = new JMenu("File");
3. JMenuItem jmiOpen = new JMenuItem("Open");
4. JMenuItem jmiClose = new JMenuItem("Close");
5. JMenuItem jmiSave = new JMenuItem("Save");
6. JMenuItem jmiExit = new JMenuItem("Exit");
7. jmFile.add(jmiOpen);
8. jmFile.add(jmiClose);
9. jmFile.add(jmiSave);
10. jmFile.addSeparator();
11. jmFile.add(jmiExit);
12. jmb.add(jmFile);

Java Programing
1. // Create the Options menu.
2. JMenu jmOptions = new JMenu("Options"); 14
3. // Create the Colors submenu.
4. JMenu jmColors = new JMenu("Colors");
5. JMenuItem jmiRed = new JMenuItem("Red");
6. JMenuItem jmiGreen = new JMenuItem("Green");
7. JMenuItem jmiBlue = new JMenuItem("Blue");
8. jmColors.add(jmiRed);
9. jmColors.add(jmiGreen);
10. jmColors.add(jmiBlue);
11. jmOptions.add(jmColors);
12. // Create the Priority submenu.
13. JMenu jmPriority = new JMenu("Priority");
14. JMenuItem jmiHigh = new JMenuItem("High");
15. JMenuItem jmiLow = new JMenuItem("Low");
16. jmPriority.add(jmiHigh);
17. jmPriority.add(jmiLow);
18. jmOptions.add(jmPriority);
Java Programing
1. // Create the Reset menu item.
2.
3.
JMenuItem jmiReset = new JMenuItem("Reset");
jmOptions.addSeparator(); jmOptions.add(jmiReset);
15
4. // Finally, add the entire options menu to the menu bar
5. jmb.add(jmOptions);
6. // Create the Help menu.
7. JMenu jmHelp = new JMenu("Help");
8. JMenuItem jmiAbout = new JMenuItem("About");
9. jmHelp.add(jmiAbout); jmb.add(jmHelp);
10. // Add action listeners for the menu items.
11. jmiOpen.addActionListener(this);
12. jmiClose.addActionListener(this);
13. jmiSave.addActionListener(this);
14. jmiExit.addActionListener(this);
15. jmiRed.addActionListener(this);
16. jmiGreen.addActionListener(this);
17. jmiBlue.addActionListener(this);
18. jmiHigh.addActionListener(this);
19. jmiLow.addActionListener(this);
20. jmiReset.addActionListener(this);
Java Programing
21. jmiAbout.addActionListener(this);
1. jfrm.add(jlab); // Add the label to the content pane.
2.
3.
// Add the menu bar to the frame.
jfrm.setJMenuBar(jmb);
16
4. jfrm.setVisible(true); // Display the frame.
5. }
6. //Handle menu item action events.
7. public void actionPerformed(ActionEvent ae) {
8. // Get the action command from the menu selection.
9. String comStr = ae.getActionCommand();
10. // If user chooses Exit, then exit the program.
11. if (comStr.equals("Exit")) System.exit(0);
12. // Otherwise, display the selection.
13. jlab.setText(comStr + " Selected");
14. }
15. public static void main(String args[]) {
16. // Create the frame on the event dispatching thread.
17. SwingUtilities.invokeLater(new Runnable() {
18. public void run() { new MenuDemo(); }
19. });
20. }
Java Programing
21. }
Add Mnemonics and Accelerators to
Menu Items 17
• In real applications: a menu usually includes support for
keyboard shortcuts à ability to select menu items rapidly.
• Two forms:
• mnemonics and
• accelerators.
• a mnemonic allows you to use the keyboard to select an
item from a menu that is already being displayed.
• An accelerator is a key that lets you select a menu item
without having to first activate the menu.

Java Programing
mnemonic [1] 18
• A mnemonic can be specified for both JMenuItem and
JMenu objects.
• Two ways to set the mnemonic for JMenuItem
• Using constructor : JMenuItem (String name, int mnem)
• Set the mnemonic : void setMnemonic (int mnem)
• mnem specifies the mnemonic. It should be one of the constants
defined in java.awt.event.KeyEvent, such as
KeyEvent.VK_F ou KeyEvent.VK_Z.
• Mnemonics are not case sensitive.

Java Programing
mnemonic [2] 19
• By default: the first matching letter in the menu item will
be underscored.
• In cases in which you want to underscore a letter other than the
first match:
void setDisplayedMnemonicIndex(int idx)
• The index of the letter to underscore is specified by idx.

Java Programing
Accelerator [1] 20
• An accelerator can be associated with a JMenuItem
object.
• It is specified by calling
void setAccelerator (KeyStroke ks)
• ks is the key combination that is pressed to select the menu item.
• KeyStroke is a class that contains several factory methods that
construct various types of keystroke accelerators.
• Example:
• static KeyStroke getKeyStroke(char ch)
• static KeyStroke getKeyStroke(Character ch, int
modifier)
• static KeyStroke getKeyStroke(int ch, int modifier)
• ch specifies the accelerator character.

Java Programing
Accelerator [2] 21
• modifier must be one or more of the following constants,
defined in the java.awt.event.InputEvent class :

• If you pass VK_A for the key character and


InputEvent.CTRL_DOWN_MASK for the modifier à the
accelerator key combination is CTRL-A.

Java Programing
1. // Create the File menu with mnemonics and accelerators.
2.

3.
jmFile.setMnemonic(KeyEvent.VK_F);
JMenuItem jmiOpen = new JMenuItem("Open", KeyEvent.VK_O);
22
4. jmiOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
5. InputEvent.CTRL_DOWN_MASK));
6. JMenuItem jmiClose = new JMenuItem("Close", KeyEvent.VK_C);
7. jmiClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
8. InputEvent.CTRL_DOWN_MASK));
9. JMenuItem jmiSave = new JMenuItem("Save", KeyEvent.VK_S);
10. jmiSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
11. InputEvent.CTRL_DOWN_MASK));
12. JMenuItem jmiExit = new JMenuItem("Exit", KeyEvent.VK_E);
13. jmiExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
14. InputEvent.CTRL_DOWN_MASK));

Java Programing
Add Images and Tooltips to Menu
Items [1] 23
• You can add images to menu items or use images
instead of text.
• Constructors:
• JMenuItem(Icon image)
• JMenuItem(String name, Icon image)
• Example:
• ImageIcon icon = new ImageIcon("AboutIcon.gif");
• JMenuItem jmiAbout = new JMenuItem("About",
icon);

Java Programing
Add Images and Tooltips to Menu
Items [2] 24
• To add an icon to a menu item (inherit from
AbstractButton)
• void setIcon(Icon defaultIcon)
• To specify horizontal alignment of image:
• void setHorizontalAlignment(int alignment)
• To specify a disabled icon:
• void setDisabledIcon(Icon disabledIcon)

Java Programing
Tooltip 25
• A tooltip is a small message that describes an item.
• It is automatically displayed if the mouse remains over
the item for a moment.
• To add a tooltip to a menu item:
• void setToolTipText(String msg)
• Example
jmiAbout.setToolTipText
("Info about the MenuDemo program.");

Java Programing
JRadioButtonMenuItem and
JCheckBoxMenuItem 26
• Menu items are the most commonly used.
• Swing defines two others: check boxes and radio buttons.
• Allow a menu to provide functionality that would otherwise
require additional, standalone components.
• Sometimes, including check boxes or radio buttons in a menu
simply seems the most natural place for a specific set of features.
• To add a check box to a menu: create a
JCheckBoxMenuItem.
• Constructors :
• JCheckBoxMenuItem(String name)
• JCheckBoxMenuItem(String name, boolean state)
• JCheckBoxMenuItem(String name, Icon icon)

Java Programing
Example: JCheckBoxMenuItem 27
1. // Use check boxes for colors. This allows
2. // the user to select more than one color.
3. JCheckBoxMenuItem jmiRed = new JCheckBoxMenuItem("Red", true);
4. JCheckBoxMenuItem jmiGreen = new JCheckBoxMenuItem("Green", false);
5. JCheckBoxMenuItem jmiBlue = new JCheckBoxMenuItem("Blue", false);

Java Programing
JRadioButtonMenuItem 28

• Constructors
• JRadioButtonMenuItem(String name)
• JRadioButtonMenuItem(String name, boolean state)
• JRadioButtonMenuItem(String name, Icon icon,
boolean state)
• Example
JRadioButtonMenuItem jmiHigh =
new JRadioButtonMenuItem("High", true);
JRadioButtonMenuItem jmiLow =
new JRadioButtonMenuItem("Low");
// Create button group for the radio button menu items.
ButtonGroup bg = new ButtonGroup();
bg.add(jmiHigh); bg.add(jmiLow);

Java Programing
Create a Popup Menu [1] 29
• A popular alternative or addition to the menu bar.
• A popup menu is activated by clicking the right mouse
button when over a component.
• Constructors
• JPopupMenu()
• JPopupMenu(String label)
• Popup menus are constructed like regular menus
• First, create a JPopupMenu object, and then add menu items to
it.
• Menu item selections are also handled in the same way: by
listening for action events.

Java Programing
Create a Popup Menu [2] 30
• The main difference between a popup menu and regular
menu: the activation process.
1. You must register a listener for mouse events.
2. Inside the mouse event handler, you must watch for the popup
trigger.
3. When a popup trigger is received, you must show the popup
menu by calling show( ).
• To listen for the popup trigger:
• Implement the MouseListener interface and
• Register the listener by calling the addMouseListener( )
method

Java Programing
Create a Popup Menu [3] 31
• Methods of MouseListener:
• void mouseClicked(MouseEvent me)
• void mouseEntered(MouseEvent me)
• void mouseExited(MouseEvent me)
• void mousePressed(MouseEvent me)
• void mouseReleased(MouseEvent me)
• Four methods of MouseEvent class are commonly
needed when activating a popup menu:
• int getX( )
• int getY( )
• boolean isPopupTrigger( )
• Component getComponent( )

Java Programing
1. // Create an Edit popup menu.
2. JPopupMenu jpu = new JPopupMenu(); 32
3. // Create the popup menu items
4. JMenuItem jmiCut = new JMenuItem("Cut");
5. JMenuItem jmiCopy = new JMenuItem("Copy");
6. JMenuItem jmiPaste = new JMenuItem("Paste");
7. // Add the menu items to the popup menu.
8. jpu.add(jmiCut); jpu.add(jmiCopy); jpu.add(jmiPaste);
9. // Add a listener for for the popup trigger.
10. jfrm.addMouseListener(new MouseAdapter() {
11. public void mousePressed(MouseEvent me) {
12. if(me.isPopupTrigger())
13. jpu.show(me.getComponent(), me.getX(), me.getY());
14. }
15. public void mouseReleased(MouseEvent me) {
16. if(me.isPopupTrigger())
17. jpu.show(me.getComponent(), me.getX(), me.getY());
18. }
Java Programing
19. });
Toolbar 33
• A toolbar is a component that can serve as both an
alternative and as an adjunct to a menu.
• A toolbar contains a list of buttons (or other components)
that give the user immediate access to various program
options.
• In general:
• Toolbar buttons show icons rather than text, although either or
both are allowed.
• Tooltips are often associated with icon-based toolbar buttons.
• Toolbars can be positioned on any side of a window by
dragging the toolbar, or they can be dragged out of the
window entirely, in which case they become free floating.

Java Programing
Create a Toolbar [1] 34
• To create a toolbar: JToolBar
• Constructors
• JToolBar ()
• JToolBar (String title)
• JToolBar (int how)
• JToolBar (String title, int how)
• To add buttons (or other components) to a toolbar: Use
add().

Java Programing
1. // Create a Debug tool bar.
2.
3.
JToolBar jtb = new JToolBar("Debug");
// Load the images.
35
4. ImageIcon set = new ImageIcon("setBP.gif");
5. ImageIcon clear = new ImageIcon("clearBP.gif");
6. ImageIcon resume = new ImageIcon("resume.gif");
7. // Create the tool bar buttons.
8. JButton jbtnSet = new JButton(set);
9. jbtnSet.setActionCommand("Set Breakpoint");
10. jbtnSet.setToolTipText("Set Breakpoint");
11. JButton jbtnClear = new JButton(clear);
12. jbtnClear.setActionCommand("Clear Breakpoint");
13. jbtnClear.setToolTipText("Clear Breakpoint");
14. JButton jbtnResume = new JButton(resume);
15. jbtnResume.setActionCommand("Resume");
16. jbtnResume.setToolTipText("Resume");
17. // Add the buttons to the toolbar.
18. jtb.add(jbtnSet); jtb.add(jbtnClear); jtb.add(jbtnResume)
19. jfrm.add(jtb, BorderLayout.NORTH);
Java Programing
Plan du cours 36
1. Menu
2. Dialog window
3. Other components: JFileChooser,
JColorChooser

Java Programing
Dialog window 37
• An independent subwindow meant to carry temporary
notice apart from the main Swing Application Window.
• Most Dialogs present an error message or warning to a
user, but Dialogs can present images, directory trees, or
just about anything compatible with the main Swing
Application that manages them.
• Several Swing component classes can directly instantiate
and display dialogs.

Java Programing
Examples of Dialog windows 38
• To create simple, standard dialogs: use the
JOptionPane class.
• The ProgressMonitor class can put up a dialog that
shows the progress of an operation.
• JColorChooser and JFileChooser supply standard
dialogs.
• To bring up a print dialog, you can use the Printing API.
• To create a custom dialog, use the JDialog class
directly.

Java Programing
Overview of Dialogs [1] 39
• Every dialog is dependent on a Frame component.
• When that Frame is destroyed: its dependent Dialogs are
destroyed, too.
• When the frame is iconified: its dependent Dialogs also
disappear from the screen.
• When the frame is deiconified: its dependent Dialogs return to
the screen.
• A Swing JDialog class inherits this behavior from the
AWT Dialog class.
• A Dialog can be modal.
• JOptionPane creates JDialogs that are modal.
• To create a non-modal Dialog: use the JDialog class directly.

Java Programing
Overview of Dialogs [2] 40
• From JDK 7: you can modify dialog window modality
behavior using the new Modality API. For more
information: click HERE.
• The JDialog class is a subclass of the
AWT java.awt.Dialog class.
• It adds a root pane container and support for a default close
operation to the Dialog object .
• When you use JOptionPane to implement a dialog,
you're still using a JDialog behind the scenes.
• Reason: JOptionPane is simply a container that can
automatically create a JDialog and add itself to the JDialog's
content pane.

Java Programing
JOptionPane Features 41
• JOptionPane provides support for laying out standard
dialogs, providing icons, specifying the dialog title and
text, and customizing the button text.
• Allow you to customize the components the dialog
displays and specify where the dialog should appear
onscreen.
• You can even specify that
an option pane put itself
into an internal frame
(JInternalFrame) instead
of a JDialog.

Java Programing
Example 42
JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.");

Java Programing
Methodes of JOptionPane 43
• showConfirmDialog()
• Asks a confirming question, like yes/no/cancel.
• showInputDialog()
• Prompt for some input.
• showMessageDialog()
• Tell the user about something that has happened.
• showOptionDialog()
• The Grand Unification of the above three.
à showXxxDialog

Java Programing
Arguments of showXxxDialog [1] 44

• Component parentComponent
• the parent component, which must be a Frame, a component inside
a Frame, or null.
• Object message
• specifies what the dialog should display in its main area.
• String title
• The title of the dialog.
• int optionType
• Specifies the set of buttons that appear at the bottom of the dialog.
• Values: DEFAULT_OPTION, YES_NO_OPTION,
YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION.

Java Programing
Arguments of showXxxDialog [2] 45
• int messageType
• determines the icon displayed in the dialog.
• Values: PLAIN_MESSAGE (without icon), ERROR_MESSAGE,
INFORMATION_MESSAGE,WARNING_MESSAGE,
QUESTION_MESSAGE.
• Icon icon
• The icon to display in the dialog.
• Object[] options
• specify the string displayed by each button at the bottom of the
dialog.
• Object initialValue
• Specifies the default value to be selected.

Java Programing
Example 46
1.
//Custom button text
2.
Object[] options = {"Yes, please", "No, thanks",
3.
"No eggs, no ham!"};
4.
int n = JOptionPane.showOptionDialog(frame,
5.
"Would you like some green eggs to go with that ham?",
6.
"A Silly Question", JOptionPane.YES_NO_CANCEL_OPTION,
7.
JOptionPane.QUESTION_MESSAGE, null, options,
8.
options[2]);

Java Programing
Obtaining user input from a dialog
window 47
• Only showInputDialog returns an Object.
• This Object is generally a String reflecting the user's choice.
• Example:
String name = JOptionPane.showInputDialog(frame,
"Please enter your name: ",
"Personal information",
JOptionPane.QUESTION_MESSAGE);

JOptionPane.showMessageDialog(frame, "Your name is " +


name,
"Your information",
JOptionPane.INFORMATION_MESSAGE);

Java Programing
Result 48

Java Programing
Create a custom dialog 49
• Create a class which extends JDialog.

Java Programing
Example 50
1. public class MyDialog extends JDialog {
2. MyDialog(JFrame parent, String title, boolean modal){
3. // We call the corresponding JDialog constructor
4. super(parent, title, modal);
5. // We specify the size of the dialog
6. this.setSize(200, 80);
7. // The position
8. this.setLocationRelativeTo(null);
9. // The box should not be resizable
10. this.setResizable(false);
11. // Finally we display it
12. this.setVisible(true);
13. }
} Java Programing
1. public class MyDialogDemo extends JFrame {
2. private JButton button = new 51
3. JButton("Invoke MyDialog");
4. public MyDialogDemo() {
5. setTitle("My JFrame"); setSize(300, 100);
6. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
7. setLocationRelativeTo(null);
8. getContentPane().setLayout(new FlowLayout());
9. getContentPane().add(button);
10. button.addActionListener(new ActionListener(){
11. public void actionPerformed(ActionEvent ae) {
12. new MyDialog(null, "Hello, my dialog", true);
13. }
14. });
15. this.setVisible(true);
16. }
17. public static void main(String[] args){
18. new MyDialogDemo();
Java Programing
19. }
Example (improved version) 52
1. public class MyDialog extends JDialog {
2. MyDialog(JFrame parent, String title, boolean modal){
3. super(parent, title, modal);
4. this.setSize(200, 80);
5. this.setLocationRelativeTo(null);
6. this.setResizable(false);
7. this.initComponent();
8. this.setVisible(true);
9. }
10. public void initComponent() {
11. /* initialize components and add them into the
12. content pane by calling
13. this.getContentPane().add(...);
14. */
15. }
Java Programing
16. }
Plan 53
1. Menu
2. Dialog window
3. Other components: JFileChooser,
JColorChooser

Java Programing
File Choosers 54
• Provide a GUI for navigating the file system, and then
either choosing a file or directory from a list, or entering
the name of a file or directory.
• To display a file chooser: use the JFileChooser API to
show a modal dialog containing the file chooser.
• Another way: add an instance of JFileChooser to a container.
• The JFileChooser API makes it easy to create open
and saved dialogs.
• To know more:
• https://docs.oracle.com/javase/tutorial/uiswing/components/filech
ooser.html

Java Programing
Example 55
1. //Create a file chooser
2. final JFileChooser fc = new JFileChooser();
3. // ...
4. //In response to a button click:
5. int returnVal = fc.showOpenDialog(aComponent);
6.

7. // ...
8.

9. if (returnVal == JFileChooser.APPROVE_OPTION) {
10. File file = fc.getSelectedFile();
11. // ...
12. } else {
13. // ...
14. } Java Programing
Color Choosers 56
• Enable users to choose from a palette of colors.
• Is a component that you can place anywhere within your
program GUI.
• The JColorChooser API also makes it easy to bring up
a dialog (modal or not) that contains a color chooser.
• To know more:
• https://docs.oracle.com/javase/tutorial/uiswing/components/color
chooser.html

Java Programing
57

QUESTION ?

Java Programing

You might also like