Friday, January 20, 2017

Jython 1. Four Buttons in a Grid

The Java Example 1, Four Buttons in a Grid, is written again, however, now in Jython.


# ex01.py
# Four Buttons in a Grid

from javafx.application import Application
from javafx.scene import Scene
from javafx.scene.layout import GridPane
from javafx.geometry import Pos

def select(i):
    print "The button selected is",i
        
class Ex01(Application):
    def start(self, stage):
        stage.setTitle("Example 1. Four Buttons in a Grid")

        grid = GridPane()
        grid.setVgap(100)
        grid.setHgap(100)
        grid.setAlignment(Pos.CENTER)

        from javafx.scene.control import Button
        button1 = Button("Button 1")
        GridPane.setConstraints(button1, 0, 0)
        button1.setOnAction(lambda e: select(1))
        
        button2 = Button("Button 2")
        GridPane.setConstraints(button2, 1, 0)
        button2.setOnAction(lambda e: select(2))
        
        button3 = Button("Button 3")
        GridPane.setConstraints(button3, 0, 1)
        button3.setOnAction(lambda e: select(3))
        
        button4 = Button("Button 4")
        GridPane.setConstraints(button4, 1, 1)
        button4.setOnAction(lambda e: select(4))
        
        grid.getChildren().addAll(button1, button2, button3, button4)
        scene = Scene(grid, 640, 480)
        stage.setScene(scene)
        stage.show()

if __name__ == '__main__':
    Application.launch(Ex01().class, [])

The output is the same with the result being printed out for which button is clicked.

No comments:

Post a Comment