Jython – Menus

Jython – Menus ”; Previous Next Most of the GUI based applications have a Menu bar at the top. It is found just below the title bar of the top-level window. The javax.swing package has elaborate facility to build an efficient menu system. It is constructed with the help of JMenuBar, JMenu and JMenuItem classes. In following example, a menu bar is provided in the top-level window. A File menu consisting of three menu item buttons is added to the menu bar. Let us now prepare a JFrame object with the layout set to BorderLayout. frame = JFrame(“JMenuBar example”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,300) frame.setLayout(BorderLayout()) Now, a JMenuBar object is activated by the SetJMenuBar() method. bar = JMenuBar() frame.setJMenuBar(bar) Next, a JMenu object having ‘File’ caption is declared. Three JMenuItem buttons are added to the File menu. When any of the menu items are clicked, the ActionEvent handler OnClick() function is executed. It is defined with the actionPerformed property. file = JMenu(“File”) newfile = JMenuItem(“New”,actionPerformed = OnClick) openfile = JMenuItem(“Open”,actionPerformed = OnClick) savefile = JMenuItem(“Save”,actionPerformed = OnClick) file.add(newfile) file.add(openfile) file.add(savefile) bar.add(file) The OnClick() event handler retrieves the name of the JMenuItem button by the gwtActionCommand() function and displays it in the text box at the bottom of the window. def OnClick(event): txt.text = event.getActionCommand() The File menu object is added to menu bar. Finally, a JTextField control is added at the bottom of the JFrame object. txt = JTextField(10) frame.add(txt, BorderLayout.SOUTH) The entire code of menu.py is given below − from javax.swing import JFrame, JMenuBar, JMenu, JMenuItem, JTextField from java.awt import BorderLayout frame = JFrame(“JMenuBar example”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,300) frame.setLayout(BorderLayout()) def OnClick(event): txt.text = event.getActionCommand() bar = JMenuBar() frame.setJMenuBar(bar) file = JMenu(“File”) newfile = JMenuItem(“New”,actionPerformed = OnClick) openfile = JMenuItem(“Open”,actionPerformed = OnClick) savefile = JMenuItem(“Save”,actionPerformed = OnClick) file.add(newfile) file.add(openfile) file.add(savefile) bar.add(file) txt = JTextField(10) frame.add(txt, BorderLayout.SOUTH) frame.setVisible(True) When the above script is executed using the Jython interpreter, a window with the File menu appears. Click on it and its three menu items will drop down. If any button is clicked, its name will be displayed in the text box control. Print Page Previous Next Advertisements ”;

Jython – Dialogs

Jython – Dialogs ”; Previous Next A Dialog object is a window that appears on top of the base window with which the user interacts. In this chapter, we shall see the preconfigured dialogs defined in the swing library. They are MessageDialog, ConfirmDialog and InputDialog. They are available because of the static method of the JOptionPane class. In the following example, the File menu has three JMenu items corresponding to the above three dialogs; each executes the OnClick event handler. file = JMenu(“File”) msgbtn = JMenuItem(“Message”,actionPerformed = OnClick) conbtn = JMenuItem(“Confirm”,actionPerformed = OnClick) inputbtn = JMenuItem(“Input”,actionPerformed = OnClick) file.add(msgbtn) file.add(conbtn) file.add(inputbtn) The OnClick() handler function retrieves the caption of Menu Item button and invokes the respective showXXXDialog() method. def OnClick(event): str = event.getActionCommand() if str == ”Message”: JOptionPane.showMessageDialog(frame,”this is a sample message dialog”) if str == “Input”: x = JOptionPane.showInputDialog(frame,”Enter your name”) txt.setText(x) if str == “Confirm”: s = JOptionPane.showConfirmDialog (frame, “Do you want to continue?”) if s == JOptionPane.YES_OPTION: txt.setText(“YES”) if s == JOptionPane.NO_OPTION: txt.setText(“NO”) if s == JOptionPane.CANCEL_OPTION: txt.setText(“CANCEL”) If the message option from menu is chosen, a message pops up. If Input option is clicked, a dialog asking for the input pops up. The input text is then displayed in the text box in the JFrame window. If the Confirm option is selected, a dialog with three buttons, YES, NO and CANCEL comes up. The user’s choice is recorded in the text box. The entire code is given below − from javax.swing import JFrame, JMenuBar, JMenu, JMenuItem, JTextField from java.awt import BorderLayout from javax.swing import JOptionPane frame = JFrame(“Dialog example”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,300) frame.setLayout(BorderLayout()) def OnClick(event): str = event.getActionCommand() if str == ”Message”: JOptionPane.showMessageDialog(frame,”this is a sample message dialog”) if str == “Input”: x = JOptionPane.showInputDialog(frame,”Enter your name”) txt.setText(x) if str == “Confirm”: s = JOptionPane.showConfirmDialog (frame, “Do you want to continue?”) if s == JOptionPane.YES_OPTION: txt.setText(“YES”) if s == JOptionPane.NO_OPTION: txt.setText(“NO”) if s == JOptionPane.CANCEL_OPTION: txt.setText(“CANCEL”) bar = JMenuBar() frame.setJMenuBar(bar) file = JMenu(“File”) msgbtn = JMenuItem(“Message”,actionPerformed = OnClick) conbtn = JMenuItem(“Confirm”,actionPerformed = OnClick) inputbtn = JMenuItem(“Input”,actionPerformed = OnClick) file.add(msgbtn) file.add(conbtn) file.add(inputbtn) bar.add(file) txt = JTextField(10) frame.add(txt, BorderLayout.SOUTH) frame.setVisible(True) When the above script is executed, the following window is displayed with three options in the menu − Message box Input Box Confirm Dialog Print Page Previous Next Advertisements ”;

Jython – Discussion

Discuss Jython ”; Previous Next Jython is the JVM implementation of the Python programming language. It is designed to run on the Java platform. Jython was created in 1997 by Jim Hugunin. It closely follows the standard Python implementation called CPython. Jython 2.7.0 was released in May 2015, which corresponds to CPython 2.7. This is an introductory tutorial, which covers the basics of Jython and explains how to handle its various modules and sub-modules. Print Page Previous Next Advertisements ”;

Jython – Modules

Jython – Modules ”; Previous Next A module is a Jython script in which one or more related functions, classes or variables are defined. This allows a logical organization of the Jython code. The Program elements defined in a module can be used in another Jython script by importing either the module or the specific element (function/class) from it. In the following code (hello.py) a function SayHello() is defined. #definition of function defSayHello(str): print “Hello “, str return To use the SayHello() function from another script, import the hello.py module in it. import hello hello.SayHello(“TutorialsPoint”) However, this will import all functions defined in the module. In order to import specific function from module use following syntax. from modname import name1[, name2[,… nameN] For example, to import only the SayHello() function, change the above script as follows. from hello import SayHello SayHello(“TutorialsPoint”) There is no need to prefix the name of the module while calling the function. Print Page Previous Next Advertisements ”;

Jython – JDBC

Jython – JDBC ”; Previous Next Jython uses the zxJDBC package that provides an easy-to-use Python wrapper around JDBC. zxJDBC bridges two standards: JDBC is the standard platform for database access in Java, and DBI is the standard database API for Python apps. ZxJDBC provides a DBI 2.0 standard compliant interface to JDBC. Over 200 drivers are available for JDBC and they all work with zxJDBC. High performance drivers are available for all major relational databases, including − DB2 Derby MySQL Oracle PostgreSQL SQLite SQL Server and Sybase. The ZxJDBC package can be downloaded from https://sourceforge.net/projects/zxjdbc/ or http://www.ziclix.com/zxjdbc/. The downloaded archive contains the ZxJDBC.jar, which should be added to the CLASSPATH environment variable. We intend to establish database connectivity with MySQL database. For this purpose, the JDBC driver for MySQL is required. Download the MySQL J connector from the following link – https://dev.mysql.com/downloads/connector/j/ and include the mysql connector java-5.1.42-bin.jar in the CLASSPATH. Login to the MySQL server and create a student table in the test database with the following structure − Field Type Width Name Varchar 10 Age Int 3 Marks Int 3 Add a few records in it. Name Age Marks Ravi 21 78 Ashok 20 65 Anil 22 71 Create the following Jython script as dbconnect.py. url = “jdbc:mysql://localhost/test” user = “root” password = “password” driver = “com.mysql.jdbc.Driver” mysqlConn = zxJDBC.connect(url, user, password, driver) mysqlConn = con.cursor() mysqlConn.execute(“select * from student) for a in mysql.fetchall(): print a Execute the above script from the Jython prompt. Records in the student table will be listed as shown below − (“Ravi”, 21, 78) (“Ashok”, 20, 65) (“Anil”,22,71) This explains the procedure of establishing JDBC in Jython. Print Page Previous Next Advertisements ”;

Jython – Functions

Jython – Functions ”; Previous Next A complex programming logic is broken into one or more independent and reusable blocks of statements called as functions. Python’s standard library contains large numbers of built-in functions. One can also define their own function using the def keyword. User defined name of the function is followed by a block of statements that forms its body, which ends with the return statement. Once defined, it can be called from any environment any number of times. Let us consider the following code to make the point clear. #definition of function defSayHello(): “optional documentation string” print “Hello World” return #calling the function SayHello() A function can be designed to receive one or more parameters / arguments from the calling environment. While calling such a parameterized function, you need to provide the same number of parameters with similar data types used in the function definition, otherwise Jython interpreter throws a TypeError exception. Example Live Demo #defining function with two arguments def area(l,b): area = l*b print “area = “,area return #calling function length = 10 breadth = 20 #with two arguments. This is OK area(length, breadth) #only one argument provided. This will throw TypeError area(length) The output will be as follows − area = 200 Traceback (most recent call last): File “area.py”, line 11, in <module> area(length) TypeError: area() takes exactly 2 arguments (1 given) After performing the steps defined in it, the called function returns to the calling environment. It can return the data, if an expression is mentioned in front of the return keyword inside the definition of the function. Live Demo #defining function def area(l,b): area = l*b print “area = “,area return area #calling function length = 10 breadth = 20 #calling function and obtaining its reurned value result = area(length, breadth) print “value returned by function : “, result The following output is obtained if the above script is executed from the Jython prompt. area = 200 value returned by function : 200 Print Page Previous Next Advertisements ”;

Jython – Layout Management

Jython – Layout Management ”; Previous Next Layout managers in Java are classes those, which manage the placement of controls in the container objects like Frame, Dialog or Panel. Layout managers maintain the relative positioning of controls in a frame, even if the resolution changes or the frame itself is resized. These classes implement the Layout interface. The following Layout managers are defined in the AWT library − BorderLayout FlowLayout GridLayout CardLayout GridBagLayout The following Layout Managers are defined in the Swing library − BoxLayout GroupLayout ScrollPaneLayout SpringLayout We shall use AWT layout managers as well as swing layout managers in the following examples. Absolute Layout Flow Layout Grid Layout Border Layout Box Layout Group Layout Let us now discuss each of these in detail. Absolute Layout Before we explore all the above Layout managers, we must look at absolute positioning of the controls in a container. We have to set the layout method of the frame object to ‘None’. frame.setLayout(None) Then place the control by calling the setBounds() method. It takes four arguments – x position, y position, width and height. For example – To place a button object at the absolute position and with the absolute size. btn = JButton(“Add”) btn.setBounds(60,80,60,20) Similarly, all controls can be placed by properly allocating position and size. This layout is relatively easy to use, but fails to retain its appearance when the window either is resized, or if the program is executed when screen resolution changes. In the following Jython script, three Jlabel objects are used to display text “phy”, “maths” and “Total” respectively. In front of these three – JTextField objects are placed. A Button object is placed above the “Total” label. First of all the JFrame window is created with a layout set to none. frame = JFrame(“Hello”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(300,200) frame.setLayout(None) Then different controls are added according to their absolute position and size. The complete code is given below − from javax.swing import JFrame, JLabel, JButton, JTextField frame = JFrame(“Hello”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(300,200) frame.setLayout(None) lbl1 = JLabel(“Phy”) lbl1.setBounds(60,20,40,20) txt1 = JTextField(10) txt1.setBounds(120,20,60,20) lbl2 = JLabel(“Maths”) lbl2.setBounds(60,50,40,20) txt2 = JTextField(10) txt2.setBounds(120, 50, 60,20) btn = JButton(“Add”) btn.setBounds(60,80,60,20) lbl3 = JLabel(“Total”) lbl3.setBounds(60,110,40,20) txt3 = JTextField(10) txt3.setBounds(120, 110, 60,20) frame.add(lbl1) frame.add(txt1) frame.add(lbl2) frame.add(txt2) frame.add(btn) frame.add(lbl3) frame.add(txt3) frame.setVisible(True) The output for the above code is as follows. Jython FlowLayout The FlowLayout is the default layout manager for container classes. It arranges control from left to right and then from top to bottom direction. In following example, a Jlabel object, a JTextField object and a JButton object are to be displayed in a JFrame using FlowLayout manager. To start with, let us import the required classes from the javax.swing package and the java.awt package. from javax.swing import JFrame, JLabel, JButton, JTextField from java.awt import FlowLayout Then create a JFrame object and set its Location as well as the size properties. frame = JFrame(“Hello”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(200,200) Set the layout manager for the frame as FlowLayout. frame.setLayout(FlowLayout()) Now declare objects for JLabel, JTextfield and JButton classes. label = JLabel(“Welcome to Jython Swing”) txt = JTextField(30) btn = JButton(“ok”) Finally add these controls in the frame by calling the add() method of the JFrame class. frame.add(label) frame.add(txt) frame.add(btn) To display the frame, set its visible property to true. The complete Jython script and its output is as given below − from javax.swing import JFrame, JLabel, JButton, JTextField from java.awt import FlowLayout frame = JFrame(“Hello”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(200,200) frame.setLayout(FlowLayout()) label = JLabel(“Welcome to Jython Swing”) txt = JTextField(30) btn = JButton(“ok”) frame.add(label) frame.add(txt) frame.add(btn) frame.setVisible(True) Jython GridLayout The Gridlayout manager allows placement of controls in a rectangular grid. One control is placed in each cell of the grid. In following example, the GridLayout is applied to a JFrame object dividing it in to 4 rows and 4 columns. A JButton object is to be placed in each cell of the grid. Let us first import the required libraries − from javax.swing import JFrame, JButton from java.awt import GridLayout Then create the JFrame container − frame = JFrame(“Hello”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,400) Now, apply GridLayout by specifying its dimensions as 4 by 4. frame.setLayout(GridLayout(4,4)) We should now use two FOR loops, each going from 1 to 4, so sixteen JButton objects are placed in subsequent cells. k = 0 frame.setLayout(GridLayout(4,4)) for i in range(1,5): for j in range(1,5): k = k+1 frame.add(JButton(str(k))) Finally set visibility of frame to true. The complete Jython code is given below. from javax.swing import JFrame, JButton from java.awt import GridLayout frame = JFrame(“Hello”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,400) frame.setLayout(GridLayout(4,4)) k = 0 for i in range(1,5): for j in range(1,5): k = k+1 frame.add(JButton(str(k))) frame.setVisible(True) The output of the above code is as follows − Jython BorderLayout The BorderLayout manager divides the container in five geographical regions and places with one component in each region. These regions are represented by defined constants as follows − BorderLayout.NORTH BorderLayout.SOUTH BorderLayout.EAST BorderLayout.WEST BorderLayout.CENTER Let us consider the following example − Jython BoxLayout The BoxLayout class is defined in the javax.swing package. It is used to arrange components in the container either vertically or horizontally. The direction is determined by the following constants − X_AXIS Y_AXIS LINE_AXIS PAGE_AXIS The integer constant specifies the axis along which the container”s components should be laid out. When the container has the default component orientation, LINE_AXIS specifies that the components be laid out from left to right, and PAGE_AXIS specifies that the components be laid out from top to bottom. In the following example, panel (of JPanel class) is added in a JFrame object. Vertical BoxLayout is applied to it and two more panels, top and bottom, are added to it. These two internal panels have two buttons each added in the horizontal Boxlayout. Let us first create the top-level JFrame window. frame = JFrame() frame.setTitle(“Buttons”) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(300, 150) The JPanel object is declared having a vertical BoxLayout. Add it in top-level frame. panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS)) frame.add(panel) In this panel, two more panels top and bottom are added

Jython – Useful Resources

Jython – Useful Resources ”; Previous Next The following resources contain additional information on Jython. Please use them to get more in-depth knowledge on this. Useful Links on Jython Jython − Jython Official Website. Jython Wiki − Wikipedia Reference for Jython. Useful Books on Jython To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Jython – Servlets

Jython – Servlets ”; Previous Next A Java servlet is the most widely used web development technique. We can use Jython to write servlets and this adds many more advantages beyond what Java has to offer because now we can make use of the Python language features as well. We shall use the NetBeans IDE to develop a Java web application with a Jython servlet. Ensure that the nbPython plugin is installed in the NetBeans installation. Start a new project to build a web application by choosing the following path – File → New Project → Java web → New Web Application. Provide the Project name and location. The IDE will create the project folder structure. Add a Java servlet file (ServletTest.java) under the source packages node in the Projects window. This will add servlet-api.jar in the lib folder of the project. Also, let the IDE create the web.xml descriptor file. Add the following code in ServletTest.java. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletTest extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType (“text/html”); PrintWriter toClient = response.getWriter(); toClient.println ( “<html> <head> <title>Servlet Test</title>” + ” </head> <body> <h1>Servlet Test</h1> </body> </html>” ); } } The web.xml file created by NetBeans will be as shown below − <web-app> <servlet> <servlet-name>ServletTest</servlet-name> <servlet-class>ServletTest</servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletTest</servlet-name> <url-pattern>/ServletTest</url-pattern> </servlet-mapping> </web-app> Build and run the project to obtain the text Servlet Test appearing in <h1> tag in the browser window. Thus, we have added a regular Java servlet in the application. Now, we shall add the Jython Servlet. Jython servlets work by means of an intermediate Java servlet is also known as PyServlet. The PyServlet.class is present in the jython standalone.jar. Add it in the WEB-INF/lib folder. The next step is to configure the web.xml to invoke the PyServlet, whenever a request for any *.py file is raised. This should be done by adding the following xml code in it. <servlet> <servlet-name>PyServlet</servlet-name> <servlet-class>org.python.util.PyServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>PyServlet</servlet-name> <url-pattern>*.py</url-pattern> </servlet-mapping> The full web.xml code will look as shown below. <web-app> <servlet> <servlet-name>ServletTest</servlet-name> <servlet-class>ServletTest</servlet-class> </servlet> <servlet> <servlet-name>PyServlet</servlet-name> <servlet-class>org.python.util.PyServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ServletTest</servlet-name> <url-pattern>/ServletTest</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>PyServlet</servlet-name> <url-pattern>*.py</url-pattern> </servlet-mapping> </web-app> Place the following Jython code in the WEB-INF folder inside the project folder as JythonServlet.py, which is equivalent to the previous ServletTest.java. from javax.servlet.http import HttpServlet class JythonServlet1 (HttpServlet): def doGet(self,request,response): self.doPost (request,response) def doPost(self,request,response): toClient = response.getWriter() response.setContentType (“text/html”) toClient.println ( “<html> <head> <title>Servlet Test</title>” + ” </head> <body> <h1>Servlet Test</h1> </body> </html>” ) Build the project and in the browser open the following URL − http://localhost:8080/jythonwebapp/jythonservlet.py The browser will show the Servlet Test in <h1> tag as in case of Java Servlet output. Print Page Previous Next Advertisements ”;

Jython – NetBeans Plugin & Project

Jython – NetBeans Plugin and Project ”; Previous Next Python and Jython support for NetBeans is available via the nbPython plugin. Download the plugin from following URL – http://plugins.netbeans.org/plugin/56795. Unzip the downloaded archive in some folder. For example – d:nbplugin. To install the NetBeans Plugin, let us follow the steps given below. Step 1 − Start the Netbeans IDE and then go to Tools/Plugin to open the Plugin Manager. Choose ‘Downloaded’ tab and browse to the folder in which the downloaded file has been unzipped. The NetBeans window will appear as shown below. Step 2 − The next step is to select all the .nbm files and click open. Step 3 − Click on the Install button. Step 4 − Accept the following license agreement to continue. Ignore the warning about untrusted source of plugins and restart the IDE to proceed. Jython Project in NetBeans Once restarted, start a new project by choosing File/New. Python category will now be available in the categories list. Choose it to proceed. If the system has Python installed, its version/versions will be automatically detected and shown in the Python platform dropdown list. However, Jython will not be listed. Click on the Manage button to add it. Click on the ‘New’ button to add a platform name and path to Jython executable. Jython will now be available in the platform list. Select from the dropdown list as shown in the following screenshot. We can now fill in the project name, location and main file in the next window. The project structure will appear in the projects window of the NetBeans IDE and a template Python code in the editor window. Build and execute the Jython project to obtain the following result in the output window of the NetBeans IDE. Print Page Previous Next Advertisements ”;