Home

Simple Graph Example

This example shows the use of a scripted object - a "graph" - on which we can call a method plot() to display points. We use a BshCanvas helper class for the component so that our drawing will be buffered (won't be erased when the window is redrawn). It's also possible to create a BshCanvas that calls back a scripted paint() method in our object to render its appearance. (another example coming)

Note in the snapshot above that we are able to refer to variables in the graph for later use. i.e. we can refere to our graph's canvas, frame, or graphics objects if we want to modify the graph's appearance, or do additional drawing. (In the example we set the Frame title).

For a slightly more interesting version of this example with some additional features see graph2.bsh

graph.bsh - A simple graph
import bsh.util.BshCanvas;   // BshCanvas simply buffers graphics

graph( int width, int height ) {
    canvas=new BshCanvas(); 
    canvas.setSize( width, height );
    frame=frame( canvas );
    graphics=canvas.getBufferedGraphics();
    // draw axis
    graphics.setColor( Color.red );
    graphics.drawLine( 0, height/2, width, height/2 );
    graphics.drawLine( width/2, 0, width/2, height );
    graphics.setColor( Color.black );

    plot(int x, int y) {
        graphics.fillOval( (x+width/2-1), (y+height/2-1), 3, 3);
        canvas.repaint();
    }

    return this;
}

drawSin( graph ) {
    for (int x=-100; x<100; x++ ) {
        y=(int)(50*Math.sin( x/10.0 ));
        graph.plot( x, y );
    }
}