In
first part of this series I showed how to create hello world application with Jython and JFace. Now we will add event listers and layouts. What application is good for if it is not reacting to user input?
Events
Listeners are special kind of classes and you will derive your class from it in order to be able to react to user actions. So we created MyListener listener. We pass reference to application object to constructor (so we could do many interesting things with it later then event happened). We yest close application on event in MyListener handleEvent method.
We connected button 'Close' with MyListener. Event will be fired then user will press this button.
Layouts
Layouts are used to organize widgets on the screen in desired order. This time we put all widgets in grid which is one column width and two rows in height.
Code:
"""
Hello world application with Jython and JFace
Part II - Event listeners and layouts
GUID of this code snippet: 53029f4d-a208-4f45-920c-07d81167daee
Author: Darius Kucinskas (c) 2008-2009
Email: d[dot]kucinskas[eta]gmail[dot]com
Blog: http://blog-of-darius.blogspot.com/
License: GPL
"""
from org.eclipse.swt import *
from org.eclipse.swt.SWT import *
from org.eclipse.swt.widgets import *
from org.eclipse.swt.layout import *
from org.eclipse.jface.window import *
class MyListener(Listener):
""" Class for event listener """
def __init__(self, app):
self.app = app
def handleEvent(self, event):
""" Close application if button is pressed """
self.app.close()
class SWTApp(ApplicationWindow):
""" Your second JFace application in jython """
def __init__(self, shell):
""" application constructor """
ApplicationWindow.__init__(self, shell)
def dispose(self):
""" dispose resources here """
pass
def createContents(self, parent):
"""
Creates the main window's contents
parent - the main window
return - control
"""
self.getShell().text = 'Second Jython & JFace App'
panel = Composite(parent, SWT.BORDER)
panel.setLayout(GridLayout(1, True))
""" set layout as one column grid """
label = Label(panel, SWT.CENTER)
label.text = 'Hello, World'
label.setLayoutData(GridData(SWT.CENTER, SWT.CENTER, False, False, 1, 1))
button = Button(panel, SWT.PUSH)
button.text = 'Close'
button.setLayoutData(GridData(SWT.CENTER, SWT.CENTER, False, False, 1, 1))
button.addListener(SWT.Selection, MyListener(self))
""" set listener which will react on event (button pressing) """
return panel
if __name__ == "__main__":
""" The application entry point """
display = Display()
shell = Shell(display)
app = SWTApp(shell)
try:
app.setBlockOnOpen(True)
app.open()
finally:
if app != None:
app.dispose()
display.dispose()
Execute your program:
Now execute your application. There it is, your second Jython and JFace application.
No comments:
Post a Comment