File: Graph.py

package info (click to toggle)
jython 2.5.3-16%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 43,772 kB
  • ctags: 106,434
  • sloc: python: 351,322; java: 216,349; xml: 1,584; sh: 330; perl: 114; ansic: 102; makefile: 45
file content (62 lines) | stat: -rw-r--r-- 1,539 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from java import awt
from math import *
from jarray import array

class Graph(awt.Canvas):
    def __init__(self):
        self.function = None

    def paint(self, g):
        if self.function is None:
            return self.error(g)

        sz = self.size
        xs = range(0, sz.width, 2)

        xscale = 4*pi/sz.width
        xoffset = -2*pi

        yscale = -sz.height/2.
        yoffset = sz.height/2.

        ys = []
        for x in xs:
            x = xscale*x + xoffset
            y = int(yscale*self.function(x)+yoffset)
            ys.append(y)
        g.drawPolyline(array(xs, 'i'), array(ys, 'i'), len(xs))

    def error(self, g):
        message = "Invalid Expression"
        g.font = awt.Font('Serif', awt.Font.BOLD, 20)
        width = g.fontMetrics.stringWidth(message)

        x = (self.size.width-width)/2
        y = (self.size.height+g.fontMetrics.height)/2
        g.drawString("Invalid Expression", x, y)

    def setExpression(self, 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)