faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 6 people (67%) answered Yes
Recently 2 of 4 people (50%) answered Yes

Entry

JPython double buffered applet (was: JPython, getting started)

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 239, Alex Rice


"""
Packages: jpython
"""
"""
Still don't know why createImage(x,y) doesn't work in the init() method. But it
works fine when I call it elsewhere, like in update(). Strang!
Here is the code I came up with for a double buffered applet. Maybe this would
be good to include in the demo applets that come with JPython?
"""
#!/usr/bin/env jpython
from java import applet, awt, lang
class DoubleBufferedApplet(applet.Applet, lang.Runnable):
    """ This class illustrates the use of JPython to create a
    double-buffered (no flicker) Java Applet. Note that from Python's
    point of view, DoubleBufferedApplet uses multiple inheritance, but
    from Java's point of view, it is just single inheritance, since
    Runnable is actually an Interface.
    """
    def init(self):
        applet.Applet.init(self)
        self.tip = '"JPython is quite nice, really!" said the Wumpus.'
        self.bgColor=awt.Color.black
        self.fgColor=awt.Color.cyan
        self.ypos = 0
        self.thread = None
        self.imageBuffer = None
        self.requestFocus()
        self.start()
    def run(self):
        while(1):
            self.ypos=self.ypos + 1
            if(self.ypos > self.getBounds().height-12):
               self.ypos = 0
            self.repaint()
            try:
                lang.Thread.sleep(50)
            except:
                pass
    def start(self):
        if not self.thread:
            self.thread = lang.Thread(self)
            self.thread.start()
    def stop(self):
        if self.thread:
            self.thread.stop()
            self.thread = None
    def paint(self, g):
        r = self.getBounds()
        g.setColor(self.bgColor);
        g.fillRect(0, 0, r.width, r.height);
        g.setColor(self.fgColor);
        g.drawString(self.tip, 20, self.ypos)
    def update(self, g):
        r = self.getBounds()
        if((not self.imageBuffer) or \
           (self.imageBuffer.getWidth(self) != r.width) or \
           (self.imageBuffer.getHeight(self) != r.height)):
            self.imageBuffer = self.createImage(r.width, r.height)
        self.paint(self.imageBuffer.getGraphics())
        g.drawImage(self.imageBuffer, 0, 0, self)
if __name__ == '__main__':
    import pawt
    pawt.test(DoubleBufferedApplet(), size=(500, 120))