import java
from java.awt import BorderLayout, Event
from javax.swing import AbstractAction,JMenuBar,JMenu
from javax.swing import JMenuItem,JButton,JFrame, JTextArea,JToolBar,KeyStroke
class CallbackAction(AbstractAction):
''' Action that calls a callback method '''
def __init__(self, name, desc, callback):
AbstractAction.__init__(self)
self.putValue(self.NAME, name)
self.putValue(self.SHORT_DESCRIPTION, desc)
self.callback = callback
def actionPerformed(self, event):
self.callback()
class DocWindow(JFrame):
''' A top-level view that displays a course document (Learning Object) '''
def __init__(self):
JFrame.__init__(self, 'Swing Demo', windowClosing=self.exit)
self.setBounds(200, 200, 200, 200)
self.makeUI()
def makeUI(self):
# Toolbar at the top
toolBar = self.makeToolBarAndMenus()
self.getContentPane().add(toolBar, BorderLayout.NORTH)
self.infoPanel = JTextArea()
self.getContentPane().add(self.infoPanel, BorderLayout.CENTER)
def makeToolBarAndMenus(self):
''' Create the toolbar and menus. They are created together because
they share many actions. Creation is in the order of the
toolbar. '''
menuBar = JMenuBar()
self.setJMenuBar(menuBar)
# File menu
fileMenu = JMenu('File')
fileMenu.setMnemonic('f')
menuBar.add(fileMenu)
toolBar = JToolBar()
# Actions - These are in the order that they appear in the toolbar
newAction = CallbackAction('New', 'Create a new file', self.new)
self.addAction(newAction, 'N', 'N', toolBar, fileMenu)
openAction = CallbackAction('Open...', 'Open a file', self.open)
self.addAction(openAction, 'O', 'O', toolBar, fileMenu)
self.saveAction = CallbackAction('Save', 'Save a file', self.save)
self.addAction(self.saveAction, 'S', 'S', toolBar, fileMenu)
fileMenu.addSeparator()
exitAction = CallbackAction('Exit', 'Exit', self.exit)
self.addAction(exitAction, 'X', None, None, fileMenu)
return toolBar
def addAction(self, action, mnemonic, accelerator, toolBar, menu):
''' Add an action to a toolbar and a menu '''
if toolBar:
toolbarButton = JButton(action)
toolBar.add(toolbarButton)
if menu:
menuItem = JMenuItem(action)
if mnemonic:
menuItem.setMnemonic(mnemonic)
if accelerator:
menuItem.setAccelerator(KeyStroke.getKeyStroke(ord(accelerator),
Event.CTRL_MASK, 0))
menu.add(menuItem)
def new(self):
self.infoPanel.append('New\n')
def open(self, filePath=None):
self.infoPanel.append('Open\n')
def save(self):
self.infoPanel.append('Save\n')
def exit(self, event=None):
java.lang.System.exit(0)
if __name__ == '__main__':
from javax.swing import JFrame, UIManager
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName() )
JFrame.setDefaultLookAndFeelDecorated(1)
frame = DocWindow()
frame.setVisible(1)
# show it
frame = DocWindow()
frame.setVisible(1)