Menus & toolbars in Jython Swing

In this part of the Jython Swing programming tutorial, we will work with menus and toolbar.

A menubar is one of the most visible parts of the GUI application. It is a group of commands located in various menus. While in console applications you had to remember all those arcane commands, here we have most of the commands grouped into logical parts. There are accepted standards that further reduce the amount of time spending to learn a new application. Menus group commands that we can use in an application. Toolbars provide a quick access to the most frequently used commands.

Simple menu

The first example will show a simple menu.

#!/usr/local/bin/jython
# -*- coding: utf-8 -*-

"""
ZetCode Jython Swing tutorial

This program creates a simple
menu.

author: Jan Bodnar
website: www.zetcode.com
last modified: November 2010
"""

from java.awt.event import KeyEvent
from java.lang import System
from javax.swing import ImageIcon
from javax.swing import JFrame
from javax.swing import JMenu
from javax.swing import JMenuBar
from javax.swing import JMenuItem


class Example(JFrame):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        menubar = JMenuBar()
        icon = ImageIcon("exit.png")

        file = JMenu("File")
        file.setMnemonic(KeyEvent.VK_F)

        fileExit = JMenuItem("Exit", icon,
            actionPerformed=self.onSelect)
        fileExit.setMnemonic(KeyEvent.VK_C)
        fileExit.setToolTipText("Exit application")

        file.add(fileExit)

        menubar.add(file)

        self.setJMenuBar(menubar)

        self.setTitle("Simple menu")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(250, 200)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def onSelect(self, e):
        System.exit(0)


if __name__ == '__main__':
    Example()

Our example will show a menu with one item. By selecting the exit menu item we close the application.

menubar = JMenuBar()

Here we create a menubar.

icon = ImageIcon("exit.png")

We will display an icon in the menu item.

file = JMenu("File")
file.setMnemonic(KeyEvent.VK_F)

We create a menu object. A menu is a popup window containing JMenuItems. Menus are located on the menubar. The menus can be accessed via the keybord as well. To bind a menu to a particular key, we use the setMnemonic() method. In our case, the menu can be opened with the ALT+F shortcut.

fileExit = JMenuItem("Exit", icon,
    actionPerformed=self.onSelect)
fileExit.setMnemonic(KeyEvent.VK_C)
fileExit.setToolTipText("Exit application")

Here we create a JMenuItem. A menu item is an object shown in a popup window of the selected menu. We also provide a shortcut for the menu item and a tooltip as well.

file.add(fileExit)

A menu item is added to the menu.

menubar.add(file)

A menu is added to the menubar.

Simple menu
Figure: Simple menu

Submenu

A submenu is a menu plugged into another menu object. The next example demonstrates this.

#!/usr/local/bin/jython
# -*- coding: utf-8 -*-

"""
ZetCode Jython Swing tutorial

This program creates a simple
submenu.

author: Jan Bodnar
website: www.zetcode.com
last modified: November 2010
"""

from java.lang import System
from java.awt.event import KeyEvent
from java.awt.event import ActionEvent
from javax.swing import JFrame
from javax.swing import JMenuBar
from javax.swing import JMenuItem
from javax.swing import JMenu
from javax.swing import ImageIcon
from javax.swing import KeyStroke


class Example(JFrame):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        menubar = JMenuBar()

        iconNew = ImageIcon("new.png")
        iconOpen = ImageIcon("open.png")
        iconSave = ImageIcon("save.png")
        iconExit = ImageIcon("exit.png")

        file = JMenu("File")
        file.setMnemonic(KeyEvent.VK_F)

        imp = JMenu("Import")
        imp.setMnemonic(KeyEvent.VK_M)

        newsf = JMenuItem("Import newsfeed list...")
        bookm = JMenuItem("Import bookmarks...")
        mail = JMenuItem("Import mail...")

        imp.add(newsf)
        imp.add(bookm)
        imp.add(mail)

        fileNew = JMenuItem("New", iconNew)
        fileNew.setMnemonic(KeyEvent.VK_N)

        fileOpen = JMenuItem("Open", iconOpen)
        fileNew.setMnemonic(KeyEvent.VK_O)

        fileSave = JMenuItem("Save", iconSave)
        fileSave.setMnemonic(KeyEvent.VK_S)

        fileExit = JMenuItem("Exit", iconExit,
            actionPerformed=self.onSelect)
        fileExit.setMnemonic(KeyEvent.VK_C)
        fileExit.setToolTipText("Exit application")
        fileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
            ActionEvent.CTRL_MASK))

        file.add(fileNew)
        file.add(fileOpen)
        file.add(fileSave)
        file.addSeparator()
        file.add(imp)
        file.addSeparator()
        file.add(fileExit)

        menubar.add(file)

        self.setJMenuBar(menubar)

        self.setTitle("Submenu")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(320, 220)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def onSelect(self, e):
        System.exit(0)


if __name__ == '__main__':
    Example()

In the example, we have three options in a submenu of a file menu.

imp = JMenu("Import")
...
file.add(imp)

A submenu is just like any other normal menu. It is created the same way. We simply add a menu to existing menu.

fileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
    ActionEvent.CTRL_MASK))

An accelerator is a key shortcut that launches a menu item. In our case, by pressing Ctrl+W we close the application.

file.addSeparator()

A separator is a horizontal line that visually separates the menu items. This way we can group items into some logical places.

Submenu
Figure: Submenu

Popup menu

In the next example, we create a popup menu.

#!/usr/local/bin/jython
# -*- coding: utf-8 -*-

"""
ZetCode Jython Swing tutorial

This program creates a popup menu.

author: Jan Bodnar
website: www.zetcode.com
last modified: November 2010
"""

from java.awt.event import MouseListener
from java.lang import System
from javax.swing import JFrame
from javax.swing import JMenuItem
from javax.swing import JPopupMenu


class Example(JFrame, MouseListener):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        self.menu = JPopupMenu()
        menuItemBeep = JMenuItem("Beep", actionPerformed=self.onBeep)

        self.menu.add(menuItemBeep)

        menuItemClose = JMenuItem("Exit", actionPerformed=self.onExit)
        self.menu.add(menuItemClose);
        self.addMouseListener(self)

        self.setTitle("Popup menu")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(250, 200)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def mouseReleased(self, e):
        if e.getButton() == e.BUTTON3:
            self.menu.show(e.getComponent(), e.getX(), e.getY())

    def onExit(self, e):
        System.exit(0)

    def onBeep(self, e):
        toolkit = self.getToolkit()
        toolkit.beep()

if __name__ == '__main__':
    Example()

In our example, we create a popup menu with two menu items.

self.menu = JPopupMenu()
menuItemBeep = JMenuItem("Beep", actionPerformed=self.onBeep)

We create a popup menu and a menu item.

def mouseReleased(self, e):
    if e.getButton() == e.BUTTON3:
        self.menu.show(e.getComponent(), e.getX(), e.getY())

We show the popup menu window at the x, y coordinates of the mouse click.

Popup menu`
Figure: Popup menu

JToolbar

Menus group commands that we can use in an application. Toolbars provide a quick access to the most frequently used commands. In Swing, the JToolBar class creates a toolbar in an application.

#!/usr/local/bin/jython
# -*- coding: utf-8 -*-

"""
ZetCode Jython Swing tutorial

In this program, we create a simple
toolbar.

author: Jan Bodnar
website: www.zetcode.com
last modified: November 2010
"""


from java.awt import BorderLayout
from java.lang import System
from javax.swing import ImageIcon
from javax.swing import JFrame
from javax.swing import JMenu
from javax.swing import JMenuBar
from javax.swing import JToolBar
from javax.swing import JButton



class Example(JFrame):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        menubar = JMenuBar()
        file = JMenu("File")
        menubar.add(file)
        self.setJMenuBar(menubar)

        toolbar = JToolBar()

        icon = ImageIcon("exit.png")

        exitButton = JButton(icon, actionPerformed=self.onClick)
        toolbar.add(exitButton)

        self.add(toolbar, BorderLayout.NORTH)

        self.setTitle("Toolbar")
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setSize(350, 250)
        self.setLocationRelativeTo(None)
        self.setVisible(True)

    def onClick(self, e):
        System.exit(0)

if __name__ == '__main__':
    Example()

The example creates a toolbar with one exit button.

toolbar = JToolBar()

A toolbar is created.

exitButton = JButton(icon, actionPerformed=self.onClick)
toolbar.add(exitButton)

We create a button and add it to the toolbar.

self.add(toolbar, BorderLayout.NORTH)

The toolbar is placed into the north part of the BorderLayout manager.

Toolbar
Figure: Toolbar

In this part of the Jython Swing tutorial, we mentioned menus and toolbars.