Jython - Menus


Most of the GUI based applications have a Menu bar at the top. It is found just below the title bar of the top-level window. The javax.swing package has elaborate facility to build an efficient menu system. It is constructed with the help of JMenuBar, JMenu and JMenuItem classes.

In following example, a menu bar is provided in the top-level window. A File menu consisting of three menu item buttons is added to the menu bar. Let us now prepare a JFrame object with the layout set to BorderLayout.

frame = JFrame("JMenuBar example")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(400,300)
frame.setLayout(BorderLayout())

Now, a JMenuBar object is activated by the SetJMenuBar() method.

bar = JMenuBar()
frame.setJMenuBar(bar)

Next, a JMenu object having ‘File’ caption is declared. Three JMenuItem buttons are added to the File menu. When any of the menu items are clicked, the ActionEvent handler OnClick() function is executed. It is defined with the actionPerformed property.

file = JMenu("File")
newfile = JMenuItem("New",actionPerformed = OnClick)
openfile = JMenuItem("Open",actionPerformed = OnClick)
savefile = JMenuItem("Save",actionPerformed = OnClick)
file.add(newfile)
file.add(openfile)
file.add(savefile)
bar.add(file)

The OnClick() event handler retrieves the name of the JMenuItem button by the gwtActionCommand() function and displays it in the text box at the bottom of the window.

def OnClick(event):
   txt.text = event.getActionCommand()

The File menu object is added to menu bar. Finally, a JTextField control is added at the bottom of the JFrame object.

txt = JTextField(10)
frame.add(txt, BorderLayout.SOUTH)

The entire code of menu.py is given below −

from javax.swing import JFrame, JMenuBar, JMenu, JMenuItem, JTextField
from java.awt import BorderLayout

frame = JFrame("JMenuBar example")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(400,300)
frame.setLayout(BorderLayout())

def OnClick(event):
   txt.text = event.getActionCommand()

bar = JMenuBar()
frame.setJMenuBar(bar)

file = JMenu("File")
newfile = JMenuItem("New",actionPerformed = OnClick)
openfile = JMenuItem("Open",actionPerformed = OnClick)
savefile = JMenuItem("Save",actionPerformed = OnClick)
file.add(newfile)
file.add(openfile)
file.add(savefile)
bar.add(file)

txt = JTextField(10)
frame.add(txt, BorderLayout.SOUTH)

frame.setVisible(True)

When the above script is executed using the Jython interpreter, a window with the File menu appears. Click on it and its three menu items will drop down. If any button is clicked, its name will be displayed in the text box control.

Jython Interpreter
Advertisements