def __init__(self, size=(640,480), title="awtGraph"): global myCanvas, myApplet if myCanvas == None: if myApplet == None: myApplet = Applet() pawt.test(myApplet, name=title, size=(size[0]+8,size[1]+30)) myCanvas = myApplet.canvas dcfg = myCanvas.getGraphics().getDeviceConfiguration() self.image = dcfg.createCompatibleImage(size[0], size[1]) Driver.__init__(self, self.image) if isinstance(myCanvas, Canvas): myCanvas.setWin(self)
y = (self.size.height+g.fontMetrics.height)/2 g.drawString("Invalid Expression", x, y) def setExpression(self, e): "@sig public void setExpression(java.lang.String e)" try: self.function = eval('lambda x: '+e) except: self.function = None self.repaint() if __name__ == '__main__': def enter(e): graph.setExpression(expression.text) expression.caretPosition = 0 expression.selectAll() p = awt.Panel(layout=awt.BorderLayout()) graph = Graph() p.add(graph, 'Center') expression = awt.TextField( text='(sin(3*x)+cos(x))/2', actionPerformed=enter) p.add(expression, 'South') import pawt pawt.test(p, size=(300, 300)) enter(None)
This example shows how to use Buttons """ from java import awt, applet class ButtonDemo(applet.Applet): def init(self): self.b1 = awt.Button('Disable middle button', actionPerformed=self.disable) self.b2 = awt.Button('Middle button') self.b3 = awt.Button('Enable middle button', enabled=0, actionPerformed=self.enable) self.add(self.b1) self.add(self.b2) self.add(self.b3) def enable(self, event): self.b1.enabled = self.b2.enabled = 1 self.b3.enabled = 0 def disable(self, event): self.b1.enabled = self.b2.enabled = 0 self.b3.enabled = 1 if __name__ == '__main__': import pawt print('oooooooooo00000000000000ooooooooooooo') pawt.test(ButtonDemo())
if __name__ == '__main__': km = Keymap() class T: def __init__(self, message): self.message = message self.__name__ = message def __call__(self): print self.message km.bind('x', T('x')) km.bind('C-x', T('C-x')) km.bind('A-x', T('A-x')) km.bind('up', T('up')) km.bind('enter', T('enter')) km.bind('tab', T('tab')) km.bind('S-tab', T('S-tab')) text = "hello\nworld" from pawt import swing, test doc = swing.text.DefaultStyledDocument() doc.insertString(0, text, None) edit = swing.JTextPane(doc) edit.keymap = km test(edit, size=(150, 80))
g.drawString("Invalid Expression", x, y) def setExpression(self, e): "@sig public void setExpression(java.lang.String e)" try: self.function = eval('lambda x: ' + e) except: self.function = None self.repaint() if __name__ == '__main__': def enter(e): graph.setExpression(expression.text) expression.caretPosition = 0 expression.selectAll() p = awt.Panel(layout=awt.BorderLayout()) graph = Graph() p.add(graph, 'Center') expression = awt.TextField(text='(sin(3*x)+cos(x))/2', actionPerformed=enter) p.add(expression, 'South') import pawt pawt.test(p, size=(300, 300)) enter(None)
self.setup_circles() def setup_circles(self): self.c1 = (self.random(300) + 25, self.random(300) + 25, self.random(150), self.random(255)) self.c2 = (self.random(300) + 25, self.random(300) + 25, self.random(150), self.random(255)) self.colliding = are_colliding(self.c1, self.c2) if self.colliding: print "Colliding" else: print "Not colliding" def circle(self, x, y, radius): self.ellipse(x, y, radius * 2, radius * 2) def draw(self): self.background(255) self.fill(self.c1[3]) self.circle(*self.c1[:3]) self.fill(self.c2[3]) self.circle(*self.c2[:3]) def mousePressed(self, arg): self.setup_circles() if __name__ == "__main__": import pawt pawt.test(CircleCollisions())
return float(self.text.getText()) except: return 0.0 def actionPerformed(self, e): self.setSlider(self.getValue()) self.controller.convert(self) def itemStateChanged(self, e): self.controller.convert(self) def adjustmentValueChanged(self, e): self.text.setText(str(e.getValue())) self.controller.convert(self) def setValue(self, v): self.text.setText(str(v)) self.setSlider(v) def setSlider(self, f): if f > self.max: f = self.max if f < 0: f = 0 self.slider.value = int(f) if __name__ == '__main__': import pawt pawt.test(Converter())
####################################### # a simple java applet coded in Python ####################################### from java.applet import Applet # get java superclass class Hello(Applet): def paint(self, gc): # on paint callback gc.drawString("Hello applet world", 20, 30) # draw text message if __name__ == '__main__': # if run stand-alone import pawt # get java awt lib pawt.test(Hello()) # run under awt loop
from java import awt, applet class ButtonFontDemo(applet.Applet): def init(self): self.font = awt.Font('Serif', 0, 24) self.b1 = awt.Button('Disable middle button', actionPerformed=self.disable) self.b2 = awt.Button('Middle button') self.b3 = awt.Button('Enable middle button', enabled=0, actionPerformed=self.enable) self.add(self.b1) self.add(self.b2) self.add(self.b3) def enable(self, event): self.b1.enabled = self.b2.enabled = 1 self.b3.enabled = 0 def disable(self, event): self.b1.enabled = self.b2.enabled = 0 self.b3.enabled = 1 if __name__ == '__main__': import pawt pawt.test(ButtonFontDemo())
d = self.size g.color = self.background g.draw3DRect(0, 0, d.width-1, d.height-1, 1) g.draw3DRect(3, 3, d.width-7, d.height-7, 1) class CoordinateArea(awt.Canvas): def __init__(self, controller): self.mousePressed = self.push self.controller = controller def push(self, e): try: self.point.x = e.x self.point.y = e.y except AttributeError: self.point = awt.Point(e.x, e.y) self.repaint() def paint(self, g): if hasattr(self, 'point'): self.controller.updateLabel(self.point) g.fillRect(self.point.x-1, self.point.y-1, 2, 2) if __name__ == '__main__': import pawt pawt.test(CoordinatesDemo(), size=(300, 200))
"""\ Create a panel showing all of the colors defined in the pawt.colors module Display the names of bright colors in black and of dark colors in white """ from java import awt from pawt import colors, test from math import sqrt p = awt.Panel() for name in dir(colors): color = getattr(colors, name) if isinstance(color, awt.Color): l = awt.Label(name, awt.Label.CENTER, background=color) intensity = sqrt(color.red**2 + color.green**2 + color.blue**2)/3 if intensity < 90: l.foreground = colors.white p.add(l) test(p, size=(700,500))
This example shows how to use Buttons """ from java import awt, applet class ButtonFontDemo(applet.Applet): def init(self): self.font = awt.Font('Serif', 0, 24) self.b1 = awt.Button('Disable middle button', actionPerformed=self.disable) self.b2 = awt.Button('Middle button') self.b3 = awt.Button('Enable middle button', enabled=0, actionPerformed=self.enable) self.add(self.b1) self.add(self.b2) self.add(self.b3) def enable(self, event): self.b1.enabled = self.b2.enabled = 1 self.b3.enabled = 0 def disable(self, event): self.b1.enabled = self.b2.enabled = 0 self.b3.enabled = 1 if __name__ == '__main__': import pawt pawt.test(ButtonFontDemo())
"""A rough translation of an example from the Java Tutorial http://java.sun.com/docs/books/tutorial/ This example shows how to use Choice """ from java import awt, applet class ChoiceDemo(applet.Applet): def init(self): self.choices = awt.Choice(itemStateChanged=self.change) for item in ['ichi', 'ni', 'san', 'yon']: self.choices.addItem(item) self.label = awt.Label() self.change() self.add(self.choices) self.add(self.label) def change(self, event=None): selection = self.choices.selectedIndex, self.choices.selectedItem self.label.text = 'Item #%d selected. Text = "%s".' % selection if __name__ == '__main__': import pawt pawt.test(ChoiceDemo())
def run(self): self.program.update() self.stop() def stop(self): self.program.quit = True self.thread = None class Panel(JPanel): def __init__(self, size): JPanel.__init__(self) self.setPreferredSize(Dimension(size[0],size[1])) self.surface = pyj2d.surface.Surface(size, BufferedImage.TYPE_INT_RGB) self.setBackground(Color.BLACK) def paintComponent(self, g2d): self.super__paintComponent(g2d) g2d.drawImage(self.surface, 0, 0, None) try: Toolkit.getDefaultToolkit().sync() except: pass if __name__ == '__main__': import pawt pawt.test(Applet(), size=_app_size)
self.setBackground(Color.BLACK) self._repainting = AtomicBoolean(False) def paintComponent(self, g2d): self.super__paintComponent(g2d) g2d.drawImage(self.surface, 0, 0, None) try: Toolkit.getDefaultToolkit().sync() except: pass self._repainting.set(False) if __name__ == '__main__': import pawt pawt.test(App(), size=_app_size) """ This information can be used to deploy a Java app online. Copy App.py to the script folder with PyJ2D on the path. Edit App.py to import your Python script, set app size, and code to link the app thread to the script application, including script setup that will be called upon app initialization and script execution statements that will update during the app thread loop. Alternatively, use App.py as a guide and edit your Python script accordingly. To test, the edited App.py script can be run directly on the desktop JVM using the command 'jython App.py', which executes the app code with the pawt module in main(). To create an app jar that can be deployed online, use jythonc available for Jython 2.2.1, with the command 'jythonc --core --deep --jar Pyj2d_App.jar App.py' to package together with Jython dependencies, or 'jythonc --jar Pyj2d_App.jar App.py' to package alone in which case jython.jar must be included. The mixer function requires Mixer.class (compiled with 'javac Mixer.java') and should be included in the jar with 'jar uvf Pyj2d_App.jar pyj2d/Mixer.class'. To update the app jar with a resources folder containing image and audio files, use command 'jar uvf Pyj2d_App.jar resources'. Note that Java apps do not start from main() rather launch from japplet subclass with the same name as the script. To run the app on desktop before deployment online, use appletviewer included with JDK package, which tests execution and whether the app conforms to the security profile. Using this method with Java 6 unsigned apps were created successfully, but if code is required that violates the security profile such as disk access, the app needs to be signed for permission. Current versions of Java requires all online apps to be signed, unless security configuration is changed. The functionality of online deployment using PyJ2D has not been maintained, creation of unsigned apps was verified using PyJ2D 0.23 (http://s3.gatc.ca/files/PyJ2D_0.23.zip). Code that can be used to launch the app is provided at the end of this file. To use appletviewer, place an edited App.html together with the app jar(s), and use command 'appletviewer App.html'. To deploy online, place the app jar(s) on a Web server and use an edited App.js and the HTML code that calls the JavaScript function to launch the app from the Web browser. Example code to launch app packaged in Pyj2d_App.jar with separate jython.jar: (edit the Pyj2d_App name and app size) HTML code for App.html file: <HTML> <BODY>
def paintTextFields(self,TFs,x=50,y=100): for TF in TFs: TF.setSize(200,25) TF.setLocation(x,y) y += 30 #Graphics,dict{str:str},int,int -> None def drawInfo(self,g,info,x,y): for att in self.infoAtts: if att!="Summary": g.drawString(att + ": " + info[att],x,y) y += 20 if not self.summaryField.isVisible(): self.summaryField.setText(info["Summary"]) self.summaryField.setVisible(True) #makes sure to save the document if the window is closed def saveBookList(e,bookList): try: bookListDoc = open(bookListPath,'w') for line in bookList.getItems(): bookListDoc.write(line + '\n') bookListDoc.close() finally: System.exit(0) if __name__=="__main__": import pawt bookList = BookList() applet = pawt.test(bookList,size = (600,600)) applet.windowClosing = lambda e: saveBookList(e,bookList.bookList)
bag = GridBag(self) bag.add(self.output, fill="BOTH", weightx=1.0, weighty=1.0, gridheight=2) bag.addRow(self.spanish, fill="VERTICAL") bag.addRow(self.italian, fill="VERTICAL") self.language = {self.spanish: "Spanish", self.italian: "Italian"} def action(self, e): list = e.source text = 'Action event occurred on "%s" in %s.\n' self.output.append(text % (list.selectedItem, self.language[list])) def change(self, e): list = e.source if e.stateChange == ItemEvent.SELECTED: select = "Select" else: select = "Deselect" text = "%s event occurred on item #%d (%s) in %s.\n" params = (select, e.item, list.getItem(e.item), self.language[list]) self.output.append(text % params) if __name__ == "__main__": import pawt pawt.test(ListDemo())
cb1 = awt.Checkbox('Checkbox 1') cb2 = awt.Checkbox('Checkbox 2') cb3 = awt.Checkbox('Checkbox 3', state=1) p1 = awt.Panel(layout=awt.FlowLayout()) p1.add(cb1) p1.add(cb2) p1.add(cb3) cbg = awt.CheckboxGroup() cb4 = awt.Checkbox('Checkbox 4', cbg, 0) cb5 = awt.Checkbox('Checkbox 5', cbg, 0) cb6 = awt.Checkbox('Checkbox 6', cbg, 0) p2 = awt.Panel(layout=awt.FlowLayout()) p2.add(cb4) p2.add(cb5) p2.add(cb6) self.setLayout(awt.GridLayout(0, 2)) self.add(p1) self.add(p2) self.validate() if __name__ == '__main__': import pawt pawt.test(CheckboxDemo())
g.color = self.background g.draw3DRect(0, 0, d.width-1, d.height-1, 1) g.draw3DRect(3, 3, d.width-7, d.height-7, 1) class CoordinateArea(awt.Canvas): def __init__(self, controller): self.mousePressed = self.push self.controller = controller def push(self, e): try: self.point.x = e.x self.point.y = e.y except AttributeError: self.point = awt.Point(e.x, e.y) self.repaint() def paint(self, g): if hasattr(self, 'point'): self.controller.updateLabel(self.point) g.fillRect(self.point.x-1, self.point.y-1, 2, 2) if __name__ == '__main__': import pawt pawt.test(CoordinatesDemo(), size=(300, 200))
####################################### # a simple java applet coded in Python ####################################### from java.applet import Applet # get java superclass class Hello(Applet): def paint(self, gc): # on paint callback gc.drawString("Hello applet world", 20, 30) # draw text message if __name__ == '__main__': # if run standalone import pawt # get java awt lib pawt.test(Hello()) # run under awt loop
"""A rough translation of an example from the Java Tutorial http://java.sun.com/docs/books/tutorial/ This example shows how to use Choice """ from java import awt, applet class ChoiceDemo(applet.Applet): def init(self): self.choices = awt.Choice(itemStateChanged = self.change) for item in ['ichi', 'ni', 'san', 'yon']: self.choices.addItem(item) self.label = awt.Label() self.change() self.add(self.choices) self.add(self.label) def change(self, event=None): selection = self.choices.selectedIndex, self.choices.selectedItem self.label.text = 'Item #%d selected. Text = "%s".' % selection if __name__ == '__main__': import pawt pawt.test(ChoiceDemo())
from java import awt, applet class TextField(applet.Applet): def init(self): self.t1 = awt.TextField('Hello there!',12) self.add(self.t1) if __name__ == '__main__': import pawt pawt.test(TextField())
fill='BOTH', weightx=1.0, weighty=1.0, gridheight=2) bag.addRow(self.spanish, fill='VERTICAL') bag.addRow(self.italian, fill='VERTICAL') self.language = {self.spanish: 'Spanish', self.italian: 'Italian'} def action(self, e): list = e.source text = 'Action event occurred on "%s" in %s.\n' self.output.append(text % (list.selectedItem, self.language[list])) def change(self, e): list = e.source if e.stateChange == ItemEvent.SELECTED: select = 'Select' else: select = 'Deselect' text = '%s event occurred on item #%d (%s) in %s.\n' params = (select, e.item, list.getItem(e.item), self.language[list]) self.output.append(text % params) if __name__ == '__main__': import pawt pawt.test(ListDemo())
"""\ Create a panel showing all of the colors defined in the pawt.colors module Display the names of bright colors in black and of dark colors in white """ from java import awt from pawt import colors, test from math import sqrt p = awt.Panel() for name in dir(colors): color = getattr(colors, name) if isinstance(color, awt.Color): l = awt.Label(name, awt.Label.CENTER, background=color) intensity = sqrt(color.red**2 + color.green**2 + color.blue**2) / 3 if intensity < 90: l.foreground = colors.white p.add(l) test(p, size=(700, 500))
Thread.sleep(5) if k!=100 and self.show: for z in range(0,len(self.dice)): self.dice[z] = 1 + int(random()*6) for z in range(0,len(self.dice)): self.g.setColor(Color.white) self.g.fillRect(x+z*60,y,40,40) self.g.setColor(Color.black) self.g.drawRect(x+z*60,y,40,40) self.drawDice(x+z*60,y,self.dice[z]) except InterruptedException: pass if self.show: self.addToList() if self.show: self.rollNum += 1 self.show = False def drawDice(self, x, y, num): if num==1 or num==3 or num==5: self.g.fillOval(x+15,y+15,10,10) if num>=2: self.g.fillOval(x+4,y+4,10,10) self.g.fillOval(x+26,y+26,10,10) if num>=4: self.g.fillOval(x+4,y+26,10,10) self.g.fillOval(x+26,y+4,10,10) if num==6: self.g.fillOval(x+4,y+15,10,10) self.g.fillOval(x+26,y+15,10,10) import pawt pawt.test(Petals(),size = (1300,200))
from java.applet import Applet import sys class HelloWorld(Applet): def paint(self, g): g.drawString("Hello from Jython %s!" % sys.version, 20, 30) if __name__ == '__main__': import pawt pawt.test(HelloWorld())
except: return 0.0 def actionPerformed(self, e): self.setSlider(self.getValue()) self.controller.convert(self) def itemStateChanged(self, e): self.controller.convert(self) def adjustmentValueChanged(self, e): self.text.setText(str(e.getValue())) self.controller.convert(self) def setValue(self, v): self.text.setText(str(v)) self.setSlider(v) def setSlider(self, f): if f > self.max: f = self.max if f < 0: f = 0 self.slider.value = int(f) if __name__ == '__main__': import pawt pawt.test(Converter())
""" from java import awt, applet class ButtonDemo(applet.Applet): def init(self): self.b1 = awt.Button('Disable middle button', actionPerformed=self.disable) self.b2 = awt.Button('Middle button') self.b3 = awt.Button('Enable middle button', enabled=0, actionPerformed=self.enable) self.add(self.b1) self.add(self.b2) self.add(self.b3) def enable(self, event): self.b1.enabled = self.b2.enabled = 1 self.b3.enabled = 0 def disable(self, event): self.b1.enabled = self.b2.enabled = 0 self.b3.enabled = 1 if __name__ == '__main__': import pawt pawt.test(ButtonDemo())
"""A rough translation of an example from the Java Tutorial http://java.sun.com/docs/books/tutorial/ This example shows how to use Label """ from java import applet from java.awt import Label, GridLayout class LabelDemo(applet.Applet): def init(self): self.setLayout(GridLayout(0, 1)) self.add(Label('Left')) self.add(Label('Center', Label.CENTER)) self.add(Label('Right', Label.RIGHT)) if __name__ == '__main__': import pawt pawt.test(LabelDemo())
for predictor in predictorList: self.graph.addValue(str(predictor), self.world.round, predictor.successRate) if SHOW_MI_MEAN: self.graph.addValue("miMean", self.world.round, self.world.miMean) if SHOW_NON_MI_MEAN: self.graph.addValue("non_miMean", self.world.round, self.non_miMean) # if self.world.round % ((b-a) / 10) == 0: self.win.refresh() def stop(self): self.interrupt = True while self.interrupt and self.isRunning: pass self.interrupt = False ############################################################################### # # for testing purposes this jython file can also be run as standalone # program outside a web-page # ############################################################################### if __name__ == "__main__": applet = InductionApplet() pawt.test(applet, size=(800,500)) applet.start() #applet.refresh()