GUI Applications. Let s start with a simple Swing application in Java, and then we will look at the same application in Jython. See Listing 16-1.

Similar documents
Part I: Learn Common Graphics Components

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

COMPSCI 230. Software Design and Construction. Swing

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

1005ICT Object Oriented Programming Lecture Notes

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

MIT AITI Swing Event Model Lecture 17

Java Swing Introduction

Graphical User Interface

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Window Interfaces Using Swing Objects

Solution register itself

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

Graphical User Interfaces. Comp 152

encompass a group of features for building Graphical User Interfaces (GUI).

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

COMP16121 Sample Code Lecture 1

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

Graphical User Interfaces (GUIs)

PIC 20A GUI with swing

Graphical User Interfaces

Graphical User Interfaces. Swing. Jose Jesus García Rueda

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

Graphical User Interface (GUI)

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Part 3: Graphical User Interface (GUI) & Java Applets

Graphical User Interface (Part-1) Supplementary Material for CPSC 233

Window Interfaces Using Swing Objects

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners

Graphical User Interface (GUI)

Introduction to the JAVA UI classes Advanced HCI IAT351

SINGLE EVENT HANDLING

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Commands. Written commands can be reused, cataloged, etc. Sometimes they also contain "undo" commands, too.

Graphic User Interfaces. - GUI concepts - Swing - AWT

Systems Programming Graphical User Interfaces

Swing from A to Z Some Simple Components. Preface

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

CS 251 Intermediate Programming GUIs: Event Listeners

Example: CharCheck. That s It??! What do you imagine happens after main() finishes?

Object-oriented programming in Java (2)

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing

Dr. Hikmat A. M. AbdelJaber

AP CS Unit 11: Graphics and Events

Client-side GUI. A simple Swing-gui for searching for proudcts

Building Java Programs Bonus Slides

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Lecture 9. Lecture

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Eclipsing Your IDE. Figure 1 The first Eclipse screen.

Swing. By Iqtidar Ali

More Swing. Chapter 14. Chapter 14 1

We are on the GUI fast track path

Java, Swing, and Eclipse: The Calculator Lab.

GUI Forms and Events, Part II

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Programming Languages and Techniques (CIS120)

JAVA NOTES GRAPHICAL USER INTERFACES

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Swing: Building GUIs in Java

Graphics User Defined Forms, Part I

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

Packages: Putting Classes Together

Final Exam CS 251, Intermediate Programming December 13, 2017

Swing: Building GUIs in Java

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

RAIK 183H Examination 2 Solution. November 10, 2014

RAIK 183H Examination 2 Solution. November 11, 2013

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

Answer on question #61311, Programming & Computer Science / Java

CS 251 Intermediate Programming GUIs: Components and Layout

Name: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces.

Introduction p. 1 JFC Architecture p. 5 Introduction to JFC p. 7 The JFC 1.2 Extension p. 8 Swing p. 9 Drag and Drop p. 16 Accessibility p.

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

Window Interfaces Using Swing. Chapter 12

Example: Building a Java GUI

H212 Introduction to Software Systems Honors

Chapter 14. More Swing

An array is a type of variable that is able to hold more than one piece of information under a single variable name.

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

Event Driven Programming

Calculator Class. /** * Create a new calculator and show it. */ public Calculator() { engine = new CalcEngine(); gui = new UserInterface(engine); }

More about GUIs GEEN163

14.2 Java s New Nimbus Look-and-Feel 551 Sample GUI: The SwingSet3 Demo Application As an example of a GUI, consider Fig. 14.1, which shows the SwingS

Chapter 12 GUI Basics

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali

Transcription:

GUI Applications The C implementation of Python comes with Tkinter for writing Graphical User Interfaces (GUIs). The GUI toolkit that you get automatically with Jython is Swing, which is included with the Java Platform by default. Similar to CPython, there are other toolkits available for writing GUIs in Jython. Because Swing is available on any modern Java installation, we will focus on the use of Swing GUIs in this chapter. Swing is a large subject, and can t be fully covered in a single chapter. In fact, there are entire books devoted to Swing. We will provide an introduction to Swing, but only enough to describe the use of Swing from Jython. For in-depth coverage of Swing, one of the many books or web tutorials, like the Swing tutorial at java.sun.com/docs/books/tutorial/uiswing provided by Sun Microsystems, should be used. Using Swing from Jython has a number of advantages over the use of Swing in Java. For example, bean properties are less verbose in Jython, and binding actions in Jython is much less verbose (in Java you have to use anonymous classes, and in Jython you can pass a function). Let s start with a simple Swing application in Java, and then we will look at the same application in Jython. See Listing 16-1. Listing 16-1. import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jbutton; import javax.swing.jframe; public class HelloWorld { } public static void main(string[] args) { JFrame frame = new JFrame("Hello Java!"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(300, 300); JButton button = new JButton("Click Me!"); button.addactionlistener( new ActionListener() { public void actionperformed(actionevent event) { System.out.println("Clicked!"); } } ); frame.add(button); frame.setvisible(true); } This simple application draws a JFrame that is completely filled with a JButton. When the button is pressed, Click Me! prints to the command line. See Figure 16-1.

**Figure 16-1. ** Click Me printed to the command line Now let s see what this program looks like in Jython (see Listing 16-2). Listing 16-2. from javax.swing import JButton, JFrame frame = JFrame('Hello, Jython!', defaultcloseoperation = JFrame.EXIT_ON_CLOSE, size = (300, 300) ) def change_text(event): print 'Clicked!' button = JButton('Click Me!', actionperformed=change_text) frame.add(button) frame.visible = True Except for the title, the application produces the same JFrame with JButton, printing Click Me! to the screen when the button is clicked. See Figure 16-2.

**Figure 16-2. **Results of the application created in Listing 16-2 Let s go through the Java and the Jython examples line by line to get a feel for the differences between writing Swing apps in Jython and Java. First the import statements: Listing 16-3. In Java import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jbutton; import javax.swing.jframe; Listing 16-4. In Jython from javax.swing import JButton, JFrame In Jython, it is always best to make imports explicit by using names, instead of from. Note that we did not need to import ActionEvent or ActionListener, since Jython s dynamic typing allowed us to avoid mentioning these classes in our code. Next, we have some code that creates a JFrame, and then sets a couple of bean properties. Listing 16-5. In Java JFrame frame = new JFrame("Hello Java!"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(300, 300);

Listing 16-6. In Jython frame = JFrame('Hello, Jython!', defaultcloseoperation = JFrame.EXIT_ON_CLOSE, size = (300, 300) ) In Java a new JFrame is created, and then the bean properties defaultcloseoperation and size are set. In Jython, we are able to add the bean property setters right inside the call to the constructor. This shortcut is covered in detail in Chapter 6. Still, it will bear some repeating here, because bean properties are so important in Swing libraries. In short, if you have bean getters and setters of the form getfoo/setfoo, you can treat them as properties of the object with the name foo. So instead of x.getfoo() you can use x.foo. Instead of x.setfoo(bar) you can use x.foo = bar. If you take a look at any Swing app above a reasonable size, you are likely to see large blocks of setters like: Listing 16-7. JTextArea t = JTextArea(); t.settext(message) t.seteditable(false) t.setwrapstyleword(true) t.setlinewrap(true) t.setalignmentx(component.left_alignment) t.setsize(300, 1) which, in our opinion, look better in the idiomatic Jython property setting style because they are so easy to read: Listing 16-8. t = JTextArea() t.text = message t.editable = False t.wrapstyleword = True t.linewrap = True t.alignmentx = Component.LEFT_ALIGNMENT t.size = (300, 1) You can also roll the setters into the constructor: t = JTextArea(text = message, editable = False, wrapstyleword = True, linewrap = True, alignmentx = Component.LEFT_ALIGNMENT, size = (300, 1) )

When you use properties rolled into the constructor,you need to watch out for the order in which the setters will be called. Generally this is not a problem, as the bean properties are not usually order dependent. The big exception is setvisible(): you probably have to set the visible property outside of the constructor after all properties have been set to avoid any strangeness while the properties are being set. Going back to our short example, the next block of code creates a JButton and binds the button to an action that prints out Click Me! Listing 16-9. In Java JButton button = new JButton("Click Me!"); button.addactionlistener( new ActionListener() { public void actionperformed(actionevent event) { System.out.println("Clicked!"); } } ); frame.add(button); Listing 16-10. In Jython def change_text(event): print 'Clicked!' button = JButton('Click Me!', actionperformed=change_text) frame.add(button) We think Jython s method is particularly nice here when compared to Java. Here we can pass a first class function change_text directly to the JButton in its constructor. This plays better than the more cumbersome Java addactionlistener, method where we need to create an anonymous ActionListener class and define its actionperformed method with all the ceremony necessary for static type declarations. This is one case where Jython s readability really stands out. This works because Jython is able to automatically recognize events in Java code if they have corresponding addevent()* and *removeevent() methods. Jython takes the name of the event and makes it accessible using the nice Python syntax as long as the event methods are public. Finally, in both examples we set the visible property to True. Again, although we could have set this property in the frame constructor, the visible property is one of those rare orderdependent properties that we want to set at the right time (and in this case, last). Listing 16-11. In Java frame.setvisible(true); Listing 16-12. In Jython frame.visible = True

Now that we have looked at a simple example, it makes sense to see what a medium sized app might look like in Jython. Because Twitter apps have become the Hello World of GUI applications these days, we will go with the trend. The following application gives the user a login prompt. When the user successfully logs in, the most recent tweets in their timeline are displayed. See Listing 16-13. Listing 16-13. Jython Twitter Client import twitter import re from javax.swing import (BoxLayout, ImageIcon, JButton, JFrame, JPanel, JPasswordField, JLabel, JTextArea, JTextField, JScrollPane, SwingConstants, WindowConstants) from java.awt import Component, GridLayout from java.net import URL from java.lang import Runnable class JyTwitter(object): def init (self): self.frame = JFrame("Jython Twitter", defaultcloseoperation = WindowConstants.EXIT_ON_CLOSE) self.loginpanel = JPanel(GridLayout(0,2)) self.frame.add(self.loginpanel) self.usernamefield = JTextField('',15) self.loginpanel.add(jlabel("username:", SwingConstants.RIGHT)) self.loginpanel.add(self.usernamefield) self.passwordfield = JPasswordField('', 15) self.loginpanel.add(jlabel("password:", SwingConstants.RIGHT)) self.loginpanel.add(self.passwordfield) self.loginbutton = JButton('Log in',actionperformed=self.login) self.loginpanel.add(self.loginbutton) self.message = JLabel("Please Log in") self.loginpanel.add(self.message) self.frame.pack() self.show() def login(self,event): self.message.text = "Attempting to Log in..." username = self.usernamefield.text try: self.api = twitter.api(username, self.passwordfield.text) self.timeline(username) self.loginpanel.visible = False self.message.text = "Logged in" except:

self.message.text = "Log in failed." raise self.frame.size = 400,800 def timeline(self, username): timeline = self.api.getfriendstimeline(username) self.resultpanel = JPanel() self.resultpanel.layout = BoxLayout(self.resultPanel, BoxLayout.Y_AXIS) for s in timeline: self.showtweet(s) scrollpane = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER) scrollpane.preferredsize = 400, 800 scrollpane.viewport.view = self.resultpanel self.frame.add(scrollpane) def showtweet(self, status): user = status.user p = JPanel() p.add(jlabel(imageicon(url(user.profile_image_url)))) p.add(jtextarea(text = status.text, editable = False, wrapstyleword = True, linewrap = True, alignmentx = Component.LEFT_ALIGNMENT, size = (300, 1) )) self.resultpanel.add(p) def show(self): self.frame.visible = True if name == ' main ': JyTwitter() This code depends on the python-twitter package. This package can be found on the Python package index (PyPi). If you have easy_install (see Appendix A for instructions on easy_install) then you can install python-twitter like this: Listing 16-14. jython easy_install python-twitter This will automatically install python-twitter s dependency: simplejson. Now you should be able to run the application. You should see the login prompt shown in Figure 16-3.

picture_5 **Figure 16-3. **Password prompt If you put in the wrong password, you should get the message shown in Figure 16-4. **Figure 16-4. **Failed login And finally, once you have successfully logged in, you should see something that looks similar to Figure 16-5.

**Figure 16-5. **Login successful!

picture_4 The constructor creates the outer frame, imaginatively called self.frame. We set defaultcloseoperation so that the app will terminate if the user closes the main window. We then create a loginpanel that holds the text fields for the user to enter username and password, and create a login button that will call the self.login method when clicked. We then add a Please log in label and make the frame visible. Listing 16-15. def init (self): self.frame = JFrame("Jython Twitter", defaultcloseoperation = WindowConstants.EXIT_ON_CLOSE) self.loginpanel = JPanel(GridLayout(0,2)) self.frame.add(self.loginpanel) self.usernamefield = JTextField('',15) self.loginpanel.add(jlabel("username:", SwingConstants.RIGHT)) self.loginpanel.add(self.usernamefield) self.passwordfield = JPasswordField('', 15) self.loginpanel.add(jlabel("password:", SwingConstants.RIGHT)) self.loginpanel.add(self.passwordfield) self.loginbutton = JButton('Log in',actionperformed=self.login) self.loginpanel.add(self.loginbutton) self.message = JLabel("Please Log in") self.loginpanel.add(self.message) self.frame.pack() self.show() The login method changes the label text and calls into python-twitter to attempt a login. It s in a try/except block that will display Log in failed if something goes wrong. A real application would check different types of exceptions to see what went wrong and change the display message accordingly. Listing 16-16. def login(self,event): self.message.text = "Attempting to Log in..." username = self.usernamefield.text try: self.api = twitter.api(username, self.passwordfield.text) self.timeline(username) self.loginpanel.visible = False self.message.text = "Logged in" except: self.message.text = "Log in failed."

raise self.frame.size = 400,800 If the login succeeds, we call the timeline method, which populates the frame with the latest tweets that the user is following. In the timeline method, we call GetFriendsTimeline from the python-twitter API; then we iterate through the status objects and call showtweet on each. All of this gets dropped into a JScrollPane and set to a reasonable size, and then it is added to the main frame. Listing 16-17. def timeline(self, username): timeline = self.api.getfriendstimeline(username) self.resultpanel = JPanel() self.resultpanel.layout = BoxLayout(self.resultPanel, BoxLayout.Y_AXIS) for s in timeline: self.showtweet(s) scrollpane = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER) scrollpane.preferredsize = 400, 800 scrollpane.viewport.view = self.resultpanel self.frame.add(scrollpane) In the showtweet method, we go through the tweets and add a JLabel with the user s icon (fetched via URL from user.profile_image_url) and a JTextArea to contain the text of the tweet. Note all of the bean properties that we had to set to get the JTextArea to display correctly. Listing 16-18. def showtweet(self, status): user = status.user p = JPanel() p.add(jlabel(imageicon(url(user.profile_image_url)))) p.add(jtextarea(text = status.text, editable = False, wrapstyleword = True, linewrap = True, alignmentx = Component.LEFT_ALIGNMENT, size = (300, 1) )) self.resultpanel.add(p)

Summary And that concludes our quick tour of Swing GUIs built via Jython. Again, Swing is a very large subject, so you ll want to look into dedicated Swing resources to really get a handle on it. After this chapter, it should be reasonably straightforward to translate the Java Swing examples you find into Jython Swing examples. Source: http://www.jython.org/jythonbook/en/1.0/guiapplications.html