CSA 1019 Imperative and OO Programming GUI and Event Handling Mr. Charlie Abela Dept. of of Artificial Intelligence
Objectives Getting familiar with UI UI features MVC view swing package layout managers event handlers event listeners event adapters Charlie Abela CSA1019: UI and Event Handling 2
UI features All applications require some kind of of user interface which allows the user to to interact with the underlying program/software. Most user interfaces have the ability to to take-in information from the user and also to to provide visual or or audible information back to to the user. Sometimes the interface has physical/hardware interactive components (e.g., a bank machine or or bank teller) and sometimes the components are software-based (e.g., menus, buttons, text fields). Charlie Abela CSA1019: UI and Event Handling 3
UI features (cont) All application programs, in in general, present two implementation issues to to the developer. the the user-interface business logic The separation between the implementation details of of these two, provides for better reusability. changing the the implementation of of user-interface will not impact on on the the way that the the logical aspects of of the the system are are handled and vice-versa Charlie Abela CSA1019: UI and Event Handling 4
Typical example Consider a simple button like one of of the the keyboard keys. There is is a clean separation between the the parts parts that that compose the the button's mechanism the the parts parts that that compose its its façade. The building block called a keyboard key is is actually composed of of two pieces. one one piece gives it it its its button-like behaviour. the the other other piece is is responsible for for its its appearance. It It is is therefore possible to to reuse the the button mechanism design, and to to replace the the key tops to to create a new key rather than designing each key from scratch. Charlie Abela CSA1019: UI and Event Handling 5
MVC Design Common implementation of of this technique in in software is is the the design pattern called Model/View/Controller (MVC) Java designers have used this as as the the basis for for each individual user interface component. Java Java components use use a separable model architecture: model + (view & controller) Furthermore, the the model, view, and controller pieces can change, even while the the component is is in in use. The result is is a very flexible user interface toolkit Charlie Abela CSA1019: UI and Event Handling 6
MVC Design (cont) The model represents the the state and lowlevel behaviour of of a component. It It manages the the state and conducts all all transformations on on that state. The model has no no specific knowledge of of either its its controllers or or its its views. The view manages the the visual display of of the the state represented by by the the model. The controller manages the the user interaction with the the model. It It provides the the mechanism by by which changes are are made to to the the state of of the the model. Using the the keyboard key example, the the model corresponds to to the the key's key's mechanism the the view view and and controller correspond to to the the key's key's façade. Charlie Abela CSA1019: UI and Event Handling 7
MVC Design (cont) It It is is ALWAYS a good idea to to separate the the model, view and controller (MVC): code code is is cleaner and and easier to to follow when the the model, view view and and controller are are separated its its possible to to have have multiple views or or controllers associated with with the the same same model. multiple models can can be be associated with with the the same same user user interface. Charlie Abela CSA1019: UI and Event Handling 8
Exercise In In this exercise you need to to separate the the model from the the view and controller Create an an application that allows you to to maintain a small database (ArrayList) to to store your DVDs. The application will need to to be be able to: to: keep keep the the DVD's title, title, year yearand and duration (i.e., (i.e., how how long long the the DVD lasts) when played (e.g., (e.g., 120 120 minutes). add addnew DVDs to to the the collection as as well well as as remove them them (they (they may may get get lost lost or or sold). list listthe the DVDs sorted by by title. title. Clearly identify which parts of of the the system represent the the model, view and controller Limit the the interface to to the the console and make effective use of of exception handling and OO concepts. Charlie Abela CSA1019: UI and Event Handling 9
JFC JFC is is short for for Java Foundation Classes Encompasses a group of of features for for building GUIs and and adding rich rich graphics functionality and and interactivity to to applications JFC contains the the following features Swing GUI GUI Components: includes everything from from buttons to to panes and and tables Pluggable Look-and-Feel Support: gives any any program that that uses uses Swing components the the choice of of look look and and feel feel Accessibility API: API: Enables assistive technologies, such such as as screen readers and and Braille displays, to to get get information from from user user interfaces Java Java 2D 2D API: API: to to easily incorporate 2D 2D graphics, text text and and images in in applications Drag-n-Drop Support: provides the the drag-n-drop ability Internationalisation: allows developers to to build build applications that that can can interact with with users users worldwide Charlie Abela CSA1019: UI and Event Handling 10
Swing First released in in Java 2 SE SE version 1.2 1.2 Is Is a powerful, flexible, but immense API includes 17 17 public packages import javax.swing.* Predecessor was AWT (Abstract Windows Toolkit) components were were automatically mapped to to platform specific components fine fine for for developing simple GUIs however they they are are considered as as heavyweight components Swing components are are less platformdependent, use less resources and are are therefore called lightweight components. Swing components are are distinguished from AWT components by by being prefixed with a J. J. E.g. E.g. JTable, JButton etc etc Charlie Abela CSA1019: UI and Event Handling 11
GUI classes These are are classified into three groups of of classes: container, helper, component Container classes: contain other components Container, JFrame, JDialog, JPanel and and JApplet Helper classes: used by by components and container classes to to draw and place objects (found in in the the AWT package) E.g. E.g. Graphics, Color and and Dimension, etc etc Component classes: encompass all all the the GUI components JList, JTextArea, JComboBox etc etc Charlie Abela CSA1019: UI and Event Handling 12
Basic GUI A frame is is the Java terminology for a window (i.e. its a window frame) represented by by the the Frame and JFrame classes in in Java used to to show information and handle user interaction has no no security restrictions i.e. i.e. can modify files, perform I/O, open network connections to to other computers, etc. The following creates a basic window frame and shows it it on the screen: JFrame frame frame = new new JFrame( MyWindow"); frame.setsize(300, 100); 100); frame.setvisible(true); Charlie Abela CSA1019: UI and Event Handling 13
FirstGUI Example The following class creates and launches a new frame. import javax.swing.*; public class class FirstGUI extends JFrame{ public FirstGUI(String title){ super(title); //Set //Set title title of of window setdefaultcloseoperation(exit_on_close); // // allow allow window to to close close setsize(300, 100); 100); //Set //Set size size of of window public static void void main(string[] args){ // // Instantiate a FirstGUI object FirstGUI frame frame = new new FirstGUI("FirstGUI"); frame.setvisible(true); //Show the the window Charlie Abela CSA1019: UI and Event Handling 14
Look and Feel It It is is possible to to change the look-and-feel of of the application windows Windows can look like standard windows applications, like standard cross-platform Java applications or or any look and feel that we would like. This is is done through the user interface manager (UIManager) try{ try{ UIManager.setLookAndFeel(anyLookAndFeel) catch(exception e){ e){ //some exception related stuff stuff JFrame.setDefaultLookAndFeelDecorated(true); // //...... now now make make the the frame frame as as usual usual Charlie Abela CSA1019: UI and Event Handling 15
Look and Feel (cont) The The "LookAndFeel" available in in Java Java include: UIManager.getCrossPlatformLookAndFeelClassName() UIManager.getSystemLookAndFeelClassName() "com.sun.java.swing.plaf.motif.motiflookandfeel" Crossplatform System Motif Charlie Abela CSA1019: UI and Event Handling 16
Components & Containers Components are objects on the application s window that have a visual representations (e.g., labels, lists, scroll bars, buttons, text fields, menubars, menus). Their intent is is to to allow the user to to interact with the underlying system. Components may be grouped together: most components in in Java can contain other components as as their sub-parts Charlie Abela CSA1019: UI and Event Handling 17
Containers Containers can contain other components (e.g., a window, JPanel, or or JApplet). are are actually components as as well (e.g., containers can contain other containers) can have their components automatically laid out using a LayoutManager (more on on this later) Charlie Abela CSA1019: UI and Event Handling 18
Containers (cont) A container of of components is is conceptually synonymous to to an an ArrayList of of Objects: Charlie Abela CSA1019: UI and Event Handling 19
Component Hierarchy Below is is a portion of of the the component hierarchy. The red classes are are Swing classes, while the the yellow ones are are AWT classes: Charlie Abela CSA1019: UI and Event Handling 20
Component Hierarchy (cont) Panels are Containers (i.e. they clearly contain many components). Containers are Components (i.e. recursive definition). All JComponents are also Containers (i.e., in in Swing, everything is is a Container) A JFrame is is a Window which is is a Container. Charlie Abela CSA1019: UI and Event Handling 21
Adding components JFrame frm frm = new new JFrame("MyApplication"); frm.getcontentpane().add(acomponent); frm.getcontentpane().add(othercomponent); frm.getcontentpane().add(anothercomponent); This was typically the the way in in which components were added to to a JFrame in in versions prior to to 1.5 1.5 The getcontentpane() of of the the JFrame had to to be be used to to get get the the frame s default panel and then through the the add addmethod of of the the contentpane a component could be be added. This is is how it it has been changed JFrame frm frm = new new JFrame("MyApplication"); frm.add(acomponent); frm.add(othercomponent); frm.add(anothercomponent); Through content pane delegation this has now been eased. Charlie Abela CSA1019: UI and Event Handling 22
JComponent Charlie Abela CSA1019: UI and Event Handling 23
Features of JComponents Location, Width and Height (in (in pixels): JComponent c =...... ; // // ask ask a component for for its its location int int x = c.getx(); int int y = c.gety(); // // ask ask a component for for its its width width or or height int int w = c.getwidth(); int int h = c.getheight(); // // change a component's location c.setlocation(new Point(100, 200)); // // change a component's width width and and height c.setsize(100, 50); 50); c.setmaximumsize(new Dimension(x, y)); y)); c.setminimumsize(new Dimension(x, y)); y)); c.setpreferredsize(new Dimension(x, y)); y)); Charlie Abela CSA1019: UI and Event Handling 24
Features of JComponents II Vertical and Horizontal Alignment options are are left, left, right, top, top, bottom or or centre (as (as specified by by class class constants) Background and Foreground Colours The The background is is the the "fill" "fill" colour behind the the text, text, while the the foreground is is usually used used as as the the text text colour. There are are many colours definitions. It s It s possible to to define specific Color objects by by specifying the the amount of of red, red, green and and blue blue in in them them as as integers Ability to to be be Enabled/Disabled to to disable a component so so that that it it cannot be be selected or or controlled by by the the user. user. Ability to to be be Hidden/Shown While a component is is hidden, it it is is invisible. By By default, components are are automatically visible (not (not JFrames though) Charlie Abela CSA1019: UI and Event Handling 25
JPanel A Panel is is the simplest container class it it is is itself contained (i.e. it it itself is is contained within a container) provides space in in which an application can attach any other component (including other panels) does not create a separate window of of its own like Frame. a panel can be considered to to be a sort of of bulletin board that can be filled with components and that can then be placed anywhere, as as a component itself. Charlie Abela CSA1019: UI and Event Handling 26
JPanels in Basic Applications An An application's window may may contain many components. It It is is often often the the case case that that an an arrangement of of components may may be be similar (or (or duplicated) within different windows. Example, an an application may may require require a a name, name, address address and and phone phone number number to to be be entered entered at at different times times in in different windows. Ideally its its best best to to share component layouts among the the similar windows within an an application. Charlie Abela CSA1019: UI and Event Handling 27
JPanels in Basic Applications (cont) Components can can be be placed inside a panel and and then then the the panel is is added to to a window (Frame). The The created panel can can be be added to to many different windows with with one one line line of of code, dramatically reducing the the amount of of GUI GUI code code Charlie Abela CSA1019: UI and Event Handling 28
Example code import javax.swing.*; import java.awt.*; public class class PanelWithComponents extends JPanel{ public PanelWithComponents(){ //Create and and add add a JLabel to to the the panel panel JLabel plainlbl = new new JLabel("SmallLabel"); plainlbl.sethorizontalalignment(jlabel.left); plainlbl.setbackground(color.red); plainlbl.setopaque(true); plainlbl.setforeground(color.white); add(plainlbl); // // Create a JButton JButton button1 = new new JButton("But1"); button1.setbackground(color.blue); button1.setforeground(color.yellow); add(button1); // // Create a 2nd 2nd JButton, with with an an icon icon JButton button2 = new new JButton(new ImageIcon("button.gif")); button2.setbackground(systemcolor.control); add(button2); // // Set Set the the background color color of of the the panel panel setbackground(color.green); Charlie Abela CSA1019: UI and Event Handling 29
Example code (cont) import javax.swing.*; public class class PanelTestFrame extends JFrame{ public PanelTestFrame(String title) { super(title); // // Must Must be be first first line line add(new PanelWithComponents()); setdefaultcloseoperation(exit_on_cl OSE); OSE); setsize(650, 200); 200); public static void void main(string[] args){ JFrame frame frame =new =new PanelTestFrame( Test"); frame.setvisible(true); Charlie Abela CSA1019: UI and Event Handling 30
Some JComponents JPanel with JLabel JButton CheckBox RadioButton Charlie Abela CSA1019: UI and Event Handling 31
Some More JComponents JScrollBar JTextPane JMenuBar Charlie Abela CSA1019: UI and Event Handling 32
Layout Managers LayoutMangers are are important to to ensure the the automatic arrangement (i.e. layout) of of the the components of of an an application A LayoutManager is is an an interface (java.awt.layoutmanager) It It defines methods necessary for for a class to to be be able to to arrange Components within a Container There are are 8 useful layout classes that implement LayoutManager: FlowLayout BorderLayout CardLayout GridLayout GridBagLayout BoxLayout GroupLayout SpringLayout Charlie Abela CSA1019: UI and Event Handling 33
Use Layout Managers So why use a LayoutManager? do do not have to to compute locations and sizes for for our components components will resize automatically when the the window is is resized interface will appear "nicely" on on all all platforms Layout managers are are set set in in containers using the the setlayout method LayoutManger lmanager = new new XXLayout(); container.setlayout(lmanager); Charlie Abela CSA1019: UI and Event Handling 34
FlowLayout components are are arranged horizontally from left to to right, like lines of of words in in a paragraph. if if no no space left on on current "line", components flow to to next line components are are cantered horizontally on on each line by by default often used to to arrange buttons in in a panel Charlie Abela CSA1019: UI and Event Handling 35
BorderLayout This is is the the default layout for for a JFrame Divides the the container into regions: north, south, east, west and center. Regions are are specified using class constants, such as as BorderLayout.NORTH BorderLayout.SOUTH A single component (which may itself be be a container) fills each region Charlie Abela CSA1019: UI and Event Handling 36
CardLayout Layout manager for for a container where each each component is is treated as as a "card" Displays components one one a time, time, only only one one is is visible at at a time time Often used used for for swapping panels of of components in in and and out out Used Used for for managing a set set of of panels that that present themselves as as a stack stack of of tabbed folders User User can can interact with with cards like like a slide slide show Charlie Abela CSA1019: UI and Event Handling 37
GridLayout Lays out its its components into a rectangular grid Often used for for calendar or or spreadsheet type user interfaces Components must be be added row by by row, left to to right Charlie Abela CSA1019: UI and Event Handling 38
Example import java.awt.*; import javax.swing.*; public class class GLManagerExample extends JFrame{ public GLManagerExample(String title) { super(title); setlayout(new GridLayout(6,8,5,5)); for for (int (int row=1; row<=6; row++) for for (int (int col=1; col<=8; col++) { JButton b = new new JButton(); if if (Math.random() < 0.5) 0.5) b.setbackground(color.black); else else b.setbackground(color.white); add(b); setdefaultcloseoperation(exit_on_close); setsize(250, 200); 200); public static void void main(string args[]) { GLManagerExample frame frame = new new GLManagerExample("Grid Layout Example"); frame.setvisible(true); Charlie Abela CSA1019: UI and Event Handling 39
Example Charlie Abela CSA1019: UI and Event Handling 40
GridBagLayout For complicated layout needs (typically very useful, since developer has full control). Also arranges components in in a grid, but the the exact grid size is is not explicitly defined. Rows and columns of of grid may have different sizes Components can occupy (i.e. span across) multiple rows and columns For each component, there is is an an elaborate set set of of constraints for for determining how much space is is used by by the the component Charlie Abela CSA1019: UI and Event Handling 41
GridBagLayout (cont) Charlie Abela CSA1019: UI and Event Handling 42
BoxLayout components are are arranged horizontally from left to to right, or or vertically from top to to bottom. much like flow layout, except there is is no no wraparound when space runs out. often used to to arrange components in in a panel Charlie Abela CSA1019: UI and Event Handling 43
GroupLayout was developed for for use by by GUI builder tools, but it it can also be be used manually. works with the the horizontal and vertical layouts separately. the the layout is is defined for for each dimension independently, however each component needs to to be be defined twice in in the the layout. Charlie Abela CSA1019: UI and Event Handling 44
SpringLayout a flexible layout manager designed for for use by by GUI builders. lets developer specify precise relationships between the the edges of of components under its its control. Example, it it is is possible to to define that that the the left left edge edge of of one one component is is a certain distance from from the the right right edge edge of of a second component. lays out the the children of of its its associated container according to to a set set of of constraints Charlie Abela CSA1019: UI and Event Handling 45
Exercise Create a user interface for for displaying recipes List List of of recipes List List of of categories Text Text Areas Charlie Abela CSA1019: UI and Event Handling 46
Events To get an interface to to "work" it it needs to to respond appropriately to to all user input such as as clicking buttons, typing in in text fields, selecting items from list boxes To do this, events must be handled An event is is something that happens in in the program based on some kind of of triggering input. typically caused (i.e., generated) by by user interaction the the component that caused the the event is is called the the source. can also be be generated internally by by the the program itself Charlie Abela CSA1019: UI and Event Handling 47
How are events used? events are are objects, so so each type of of event is is represented by by a distinct class (similar to to the the way exceptions are are distinct classes) low-level events represent windowsystem occurrences or or low-level input such as as mouse and key events and component, container, focus, and window events. some events may be be ignored, some may be be handled through written event handlers which are are also known as as listeners. nothing happens in in a program UNLESS an an event occurs. Java applications are are thus considered to to be be event-driven. Charlie Abela CSA1019: UI and Event Handling 48
How events work Charlie Abela CSA1019: UI and Event Handling 49
Event Loop An An Event Loop is is an an endless loop that waits for for events to to occur: events are are queued (lined up up on on a first-come-firstserved basis) in in a buffer events are are handled one one at at a time time by by an an event handler (i.e., (i.e., code code that that evaluates when event occurs) everything done done in in an an application MUST go go through this this loop loop Charlie Abela CSA1019: UI and Event Handling 50
Event Loop (cont) While each event is is being handled, JVM is is unable to to process any other events. Issues event handling code code must must not not take take too too long long to to complete. Otherwise the the JVM JVM will will not not take take any any more more events from from the the queue. applications may may seem seem to to "hang, i.e. i.e. the the screen no no longer updates, and and all all components seem seem to to freeze up up Charlie Abela CSA1019: UI and Event Handling 51
Listeners A listener: acts on on (i.e. handles) the the event notification. must be be registered so so that it it can be be notified about events from a particular source. can be be an an instance of of any class (as (as long as as the the class implements the the appropriate listener interface) When creating a GUI: decide what types of of events need to to be be handled inform Java which ones will be be handled by by registering the the event handlers (i.e. the the listeners) write the the event handling code for for each event Charlie Abela CSA1019: UI and Event Handling 52
Types of events The most common event types include: Action Events: clicking buttons, selecting items from lists etc.. Component Events: changes in in the the component's size, position, or or visibility. Focus Events: gain or or lose the the ability to to receive keyboard input. Key Events: key presses; generated only by by the the component that has the the current keyboard focus. Mouse Events: mouse clicks and the the user moving the the cursor into or or out of of the the component's drawing area. Mouse Motion Events: changes in in the the cursor's position over the the component. Container Events: component has been added to to or or removed from the the container. Charlie Abela CSA1019: UI and Event Handling 53
Associated Listeners Whenever events need need to to be be captured, an an associated list list of of defined interfaces called Listeners must must be be implemented Each Each listener interface defines one one or or more more methods that that MUST be be implemented in in order order for for the the event to to be be handled properly. ActionEvent generated when when a a button button is is pressed, pressed, a a menu menu item item selected, pressing enter enter key key in in a a text text field field Listener Listener Interface: ActionListener Method Method to to implement actionperformed(actionevent e) e) KeyEvent pressing and/or releasing a key key while within a component Listener Interface: KeyListener Methods to to implmement; keypressed(keyevent e) e) keyreleased(keyevent e) e) keytyped(keyevent e) e) Charlie Abela CSA1019: UI and Event Handling 54
Associated Listeners WindowEvent open/close, activate/deactivate, iconify/de-iconify a a window window Listener Listener Interface: WindowListener Method Method to to implement windowopened(windowevent e) e) windowclosed(windowevent e) e) windowclosing(windowevent e) e) windowactivated(windowevent e) e) windowdeactivated(windowevent e) e) windowiconified(windowevent e) e) windowdeiconified(windowevent e) e) MouseEvent pressing/releasing/clicking a a mouse mouse button, button, moving moving a a mouse mouse onto onto or or away away from from a a component Listener Listener Interface: MouseListener Methods to to implement mouseclicked(mouseevent e) e) mouseentered(mouseevent e) e) mouseexited(mouseevent e) e) mousepressed(mouseevent e) e) mousereleased(mouseevent e) e) Charlie Abela CSA1019: UI and Event Handling 55
Register for events To register for an event add the the listener (event handler) to to the the component by by using an an addxxxlistener() method (where XXX depends on on the the type of of event to to be be handled). but1.addactionlistener(actionlistener but1list); pan1.addmouselistener(mouselistener pan1list); app.addwindowlistener(windowlistener applist); but1list, pan1list and applist can be instances of of any class that implements the specific Listener interface. Charlie Abela CSA1019: UI and Event Handling 56
Example public class class EventTest extends JFrame implements ActionListener{ public EventTest(String name) name) { super(name); JButton abutton = new new JButton("Hello"); add(abutton); // // Plug-in the the button's event event handler abutton.addactionlistener(this); setdefaultcloseoperation(exit_on_close); setsize(200, 200); 200); /*Must write write this this method since since EventTest implements the the ActionListener interface*/ public void void actionperformed(actionevent e) e) { System.out.println( button pressed"); public static void void main(string[] args){ JFrame frame frame = new new EventTest( Event Listener"); frame.setvisible(true); Charlie Abela CSA1019: UI and Event Handling 57
Handling events from multiple components TextArea Buttons TextField public void void actionperformed(actionevent event){ if(event.getsource() instanceof JButton){ JButton clicked =(JButton)event.getSource(); if if (clicked == == addbutton) { addtext(inputline.gettext()); else{ else{ cleartext( ); ); else{ else{ //the //the event event source is is inputline addtext(inputline.gettext()); private void void addtext(string newline){ textarea.append(newline + NEWLINE); inputline.settext(""); private void void cleartext( ) { textarea.settext(empty_string); inputline.settext(empty_string); Charlie Abela CSA1019: UI and Event Handling 58
More on registering event handlers There are various ways in in which event handlers can be registered with specific components: same class implements the the specific interfaces needed (seen) separate class implements the the needed interfaces an "inner" class is is used which implements the the required interfaces through an an anonymous subclass of of an an Adapter class or or a Listener interface Charlie Abela CSA1019: UI and Event Handling 59
Same class Advantages: Simple Disadvantages: must write methods for for ALL events in in the the interface. can get get messy/confusing if if the the class has many components that trigger the the same events or or if if it it handles many different types of of events. public class class TestClass extends JFrame implements MouseListener { // // registering MouseListener..... acomponent.addmouselistener(this); // // Some Some more more of of your your code code public void void mouseclicked(mouseevent e) e) {; {; public void void mouseentered(mouseevent e) e) {; {; public void void mouseexited(mouseevent e) e) {; {; public void void mousepressed(mouseevent e) e) {; {; public void void mousereleased(mouseevent e {; {; Charlie Abela CSA1019: UI and Event Handling 60
Using a separate class Advantages: nice separation between class code and the the event handlers. handler can be be reused by by other classes Disadvantages: can end up up with a lot lot of of classes and class files can be be confusing as as to to which classes are are just event handler classes public class class TestClass extends JFrame{ // // registering the the listener...... { button.addactionlistener(new ButtonListener(this)); // // Some Some more more of of your your code code public class class ButtonListener implements ActionListener{ public void void actionperformed(actionevent e){ e){ // // code code when when button is is clicked Charlie Abela CSA1019: UI and Event Handling 61
Using an inner class Advantages: nice nice separation between class class code code and and the the event handlers. handler can can be be reused in in different situations within the the class class inner class classhas access to to the the methods and and fields of of the the outer outer class class Disadvantages: can can still still end end up up with with a lot lot of of class class names to to remember public class class TestClass extends JFrame{ // // registering the the listener...... { button.addactionlistener(new ButtonListener()); // // Some Some more more code code class class ButtonListener implements ActionListener{ public void void actionperformed(actionevent e){ e){ // // code code when when button is is clicked Charlie Abela CSA1019: UI and Event Handling 62
Use an anonymous class Advantages: nice and compact do do not need to to come up up with class names and reduces complexity only need to to handle one event instead of of worrying about all all events in in the the interface. Disadvantages: need to to get get accustomed to to the the syntax requires event handler code to to be be specified where listener is is registered (unless helper methods are are used) Charlie Abela CSA1019: UI and Event Handling 63
Use an anonymous class public class class TestClass extends JFrame{ // // register a listener...... { but1.addactionlistener(new ActionListener(){ public void void actionperformed(actionevent e){ e){ //code to to execute when when button is is clicked ); ); // // more more code code here here Charlie Abela CSA1019: UI and Event Handling 64
Adapter classes To To avoid having to to implement all all the the methods declared by by an an listener s interface the the defined Adapter classes can be be used. Adapter classes exist for for each listener interface that has more than one method specified MouseListener has has MouseAdapter MouseMotionListener has has MouseMotionAdapter DocumentListener has has DocumentAdapter WindowListener has has WindowAdapter ActionListener does NOT have an an adapter class since it it has only one method class class ClickHandler extends MouseAdapter{ public void void mouseclicked(mouseevent e){ e){ System.out.println("Do Something"); addmouselistener(new MouseAdapter(){ public void void mouseclicked(mouseevent e){ e){ System.out.println("Do Something"); ); ); Charlie Abela CSA1019: UI and Event Handling 65
Graphics class an abstract class that provides for a device independent graphics interface to to display figures and images on screen on different platforms whenever a component is is displayed the JVM automatically creates a Graphics object for that component the Graphics class is is part of of the java.awt.* package Charlie Abela CSA1019: UI and Event Handling 66
Graphics class // Draw a line from (x1, y1) to (x2,y2) public abstract void drawline(int x1, int y1, int x2, int y2); // Draw a rectangle with its top left at (x, y) having the given width and height public void drawrect(int x, int y, int width, int height); /*Draw a filled rectangle with its top left at (x, y) having the given width and height*/ public abstract void fillrect(int x, int y, int width, int height); /*Erase a rectangular area by filling it in with the background color*/ public abstract void clearrect(int x, int y, int width, int height); /*Draw an oval with its top left at (x, y) having the given width and height*/ public abstract void drawoval(int x, int y, int width, int height); /*Draw a filled oval with its top left at (x, y) having the given width and height*/ public abstract void filloval(int x, int y, int width, int height); Charlie Abela CSA1019: UI and Event Handling 67
Problem with resizing: component repainting changing the the size size of of a component, automatically triggers a repainting process for for that that component this this resizing may may cause unwanted effects over over the the components E.g. E.g. a a drawn drawn line line added added to to a a panel panel will will get get erased erased each each JComponent has has a repaint() method that that is is called by by the the JVM JVM automatically when the the window is is resized in in order to to redraw the the component. JVM JVM redraws these these components, but but it it will will not not automatically redraw anything that that may may have have been been drawn manually, unless its its instructed to. to. The Therepaint() method actually calls calls a method called paintcomponent(graphics g) g) the the default inherited paintcomponent() method does does not not know what what needs to to be be painted. In In order to to instruct it it to to actually redraw stuff, stuff, it it needs to to be be overridden by by a user-defined paintcomponent() method which will will specify exactly how how to to draw draw the the graphics. Charlie Abela CSA1019: UI and Event Handling 68
Example: Draw Squares public public class class SquareCanvas SquareCanvas extends extends JPanel{ JPanel{ // // Keep Keep track track of of all all square square center center positions positions private private ArrayList<Point> squares; squares; public public SquareCanvas(){ SquareCanvas(){ squares squares = new new ArrayList<Point>(); setbackground(color.white); addmouselistener(new MouseAdapter(){ MouseAdapter(){ public public void void mousepressed(mouseevent event){ event){ squares.add(event.getpoint()); // // this this will will call call paintcomponent() repaint(); repaint(); ); ); //displaying //displaying the the contents contents of of the the canvas canvas public public void void paintcomponent(graphics graphics) graphics) { // // Draw Draw the the component component as as before before (default (default look) look) super.paintcomponent(graphics); // // draw draw all all of of the the squares squares graphics.setcolor(color.black); for(point for(point center: center: squares) squares) graphics.drawrect(center.x - 20, 20, center.y center.y -20, -20, 40, 40, 40); 40); public public static static void void main(string main(string args[]) args[]) { JFrame JFrame frame frame = new new JFrame("Square JFrame("Square Drawing"); Drawing"); frame.add(new frame.add(new SquareCanvas()); frame.setsize(300, 300); 300); frame.setvisible(true); Charlie Abela CSA1019: UI and Event Handling 69
Draw Squares Charlie Abela CSA1019: UI and Event Handling 70
Move a Message public class class MovableMessage extends JPanel{ private String message = "Welcome to to Java"; private int int x=20, x=20, y =20; =20; public MovableMessage(String s){ s){ message = s; s; addmousemotionlistener(new MouseMotionAdapter(){ public void void mousedragged(mouseevent e){ e){ x = e.getx(); y = e.gety(); repaint(); ); ); public void void paintcomponent(graphics g){ g){ super.paintcomponent(g); g.drawstring(message, x, x, y); y); public static void void main(string[] args){ JFrame fr fr = new new JFrame( MoveMessage"); fr.add(new MovableMessage()); fr.setdefaultcloseoperation(jframe.exit_on_ CLOSE); fr.setsize(300, 300); 300); fr.setvisible(true); Charlie Abela CSA1019: UI and Event Handling 71
Move a Message Charlie Abela CSA1019: UI and Event Handling 72