Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1
Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware and software of different machines has different GUI capabilities Different operating systems implement the same GUI concepts differently 2
Abstract Window Toolkit (AWT) First released in 1995 with Sun s first Java release Thin abstract layer between the Java view of a user interface and the underlying hardware/software For instance AWT checkbox: maps to Windows checkbox on a Windows machine, maps to X checkbox on Unix machine Simple, but not hardware independent 3
Swing Coded in 1997 (Released Java 1.2) Name derived from code name because Sun programers liked swing music Deeper interface less dependent on machine / operating system In the process of being replaced by JavaFX JavaFX contains a GUI building tool Makes the creation of a GUI simpler, but Hides the details of the GUI from the coder so we won t start there 4
Graphics Basics Your screen is a two dimensional array of pixels Think of each pixel as having an (x,y) coordinate The upper left hand side of the screen is (0,0) The X axis increases from left to right The Y axis increases from top to bottom 5
Binghamton (0,0) X (1920,0) Y (0,1080) 6
Single Pixel Each pixel is described by three numbers 0-255 Amount of Red Amount of Green Amount of Blue Higher numbers are brighter Black is 0,0,0 White is 255,255,255 7
Swing s Job Enable the programmer to describe what should go on the screen In some relatively high level, abstract way Translate the programmer description to pixels (render) Enable the user to interact with the screen Select an active window Move the graphical (mouse) cursor in that window Mouse button clicks and wheel motion Touch screen motions Keyboard key-press Enable the programmer to define responses to user actions 8
Swing Strategy Divide and Conquer Everything on the screen can be thought of as a rectangular area on the screen called a Component JComponent is an abstract class in Swing JComponent class manages things like: rendering the component Handle drag/drop Support key bindings Manage the application wide look and feel of the component Components may contain sub-components! 9
Container Components Container is an abstract class which extends Component Add/Remove components to/from a container Find the parent of a component (direct container) Lay out the contained components Give hints about how I should be laid out in my container preferred, minimum, maximum size Alignment vs other in the X and Y directions Orientation See: http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html 10
Top Level Components Designed to interact with underlying machine / operating system / application software Top level components are sub-classes of Container To create a new application window, use JFrame To create a sub-window within (say) a browser, use JApplet To create a sub-window (e.g. popup), use JDialog 11
Class Hierarchy (so far) Component Container JFrame JDialog JApplet 12
Class Hierarchy (in reality) awt.component awt.container awt.window awt.panel awt.frame awt.dialog applet.applet swing.jframe swing.jdialog swing.japplet 13
Text Based Components Like JLabel (simplest) String text field Rendered by bitmapping each character A font is an array of bitmaps for each Unicode character Different fonts look different Includes letter size and style e.g. italic, bold, etc. Fonts do not specify color of background or foreground Bit on implies foreground Bit off implies background 14
Investigating Rendering Swing paints a component when requested to System Requests When the component is first made visible on the screen When the component is resized When the component was damaged and needs repair e.g. uncovered Program Requests The program changed the component and wants the user to see the change The component has a paint(graphics g) method This is invoked by swing whenever rendering is required Override the paint method to change how a component is rendered Don t invoke the paint method! Swing does that for you (repaint instead) 15
What s in a paint method? Paint uses the Graphics object passed as a parameter Graphics has methods to draw and fill things on the screen void drawline(intx1,int y1,int x2, int y2) void fillrect(int x,int y,int width, int height) void drawstring(string str, int x, int y) void drawimage(image img, int x, int y, ) Most of the time, we don t need to override paint the Swing classes already do that for us 16
Common Look and Feel Common look and feel information kept in the Graphics object Transform from user coordinates to pixel X and Y Clipping coordinates Boundaries Background/Foreground Colors Font Component has methods to modify this state information 17
The Event Loop GUI s are managed by an endless loop called the event loop Within this loop, Swing checks for user input If an event occurs, tasks are dispatched Events are user input, timer events, system events, etc The dispatched tasks can: Read the user input Update the screen Do calculations Dispatch future tasks Optionally exit the loop 18
BootStrapping public static void main(string[] args) { javax.swing.swingutilities.invokelater( new Runnable() { public void run() { createandshowgui(); } } ); } } 19
invokelater invokelater is a static method in the SwingUtilities class Adds it s argument to the end of the AWT event list Starts the AWT event handler When the AWT event handler finds an object on its event list, it invokes object.run() 20
Anonymous Inner Class public static void main(string[] args) { javax.swing.swingutilities.invokelater( new Runnable() { public void run() { createandshowgui(); } } ); } } Runnable is an interface 21
Using Swing directly If a Swing component does everything you want it to, use it as it stands For instance, in helloworld, all we want to do is put up a window that says hello. We can use JFrame to create a frame, and Jlabel to create a label No extra work required 22
Extending Swing If we want to extend the capabilities of Swing components, we can create child classes Override the methods we want to change For instance, add a shape to a label See MyCircle.java See CircleDemo.java 23
Dynamic GUIs So far, our GUI s have been pretty static How do we React to a keypress or button press? Alter the GUI? Do more stuff? How do we prevent getting inundated by actions? Moving a cursor may generate thousands of (x,y) cursor positions Just grabbing a window and moving it can alter The window that s moving Each window it moves over 24
Callbacks Tell a library function you want a callback by passing a function as an argument. Terminology: Registering a callback Agreement on what triggers invocation of a callback function Agreement on what arguments are passed to the callback function Agreement on interpretation of returned value from callback 25
Swing Callback Implementation Components with actions (like a button which can be pressed) have an addactionlistener(actionlistener l) method to register a callback to occur when the button is pressed. Actually, there can be multiple listeners an arraylist of listeners is kept ActionListener is an interface that requires method ActionPerformed When you code an application class, implement ActionListener Whenever an action is performed that you have registered to listen to, your ActionPerformed method will be invoked 26
The ActionEvent Class Whenever an action (like a button press) occurs, Swing generates an ActionEvent The ActionEvent has information about what action occurred, and at what time An ActionEvent object is the argument to an action listener actionperformed method Use this argument to determine which action occurred So a single actionperformed method can handle multiple buttons 27
The ActionCommand String To keep track of which button is which, a button has an ActionCommand string, set by the setactioncommand method The action command string is copied to an ActionEvent ActionEvent has a getactioncommand method to retrieve the ActionCommand string In your actionperformed method, determine which button was pressed by checking e.getactioncommand() 28
Managing Actions Add implements ActionListener to your class Add actionperformed method to your class public void actionperformed(actionevent e) { For each button: Invoke button.setactioncommand( <uniquestring> ) Invoke button.addactionlistener(this) Add: if ( <uniquestring>".equals(e.getactioncommand())) { } to your actionperformed method 29
Action Processing 1. User clicks on button 2. Triggers an event in the event loop 3. Event triggers event processing code in Swing library 4. For each actionlistener, invoke listener.actionperformed(event) 5. You registered as a listener, so your actionperformed method is invoked 6. You check the actioncommand associated with the event to figure out which button called you 7. You perform whatever action is required in response to the button push 30
Example Button Managment See example code in Swing Tutorial under CircleDemo2.java 31
Much More We have barely scratched the surface Many sophisticated widgets in the Swing library Radio Buttons Combo Box Text File Select Menu Bar Popup Menu Progress Bar Scroll bar 32