CSA 1019 Imperative and OO Programming

Size: px
Start display at page:

Download "CSA 1019 Imperative and OO Programming"

Transcription

1 CSA 1019 Imperative and OO Programming GUI and Event Handling Mr. Charlie Abela Dept. of of Artificial Intelligence

2 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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., 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

10 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

11 Swing First released in in Java 2 SE SE version Is Is a powerful, flexible, but immense API includes 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

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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 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

23 JComponent Charlie Abela CSA1019: UI and Event Handling 23

24 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

25 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

26 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

27 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

28 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

29 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

30 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

31 Some JComponents JPanel with JLabel JButton CheckBox RadioButton Charlie Abela CSA1019: UI and Event Handling 31

32 Some More JComponents JScrollBar JTextPane JMenuBar Charlie Abela CSA1019: UI and Event Handling 32

33 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

34 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

35 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

36 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

37 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

38 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

39 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

40 Example Charlie Abela CSA1019: UI and Event Handling 40

41 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

42 GridBagLayout (cont) Charlie Abela CSA1019: UI and Event Handling 42

43 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

44 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

45 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

46 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

47 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

48 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

49 How events work Charlie Abela CSA1019: UI and Event Handling 49

50 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

51 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

52 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

53 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

54 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

55 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

56 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

57 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

58 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

59 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

60 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

61 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

62 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

63 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

64 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

65 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

66 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

67 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

68 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

69 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

70 Draw Squares Charlie Abela CSA1019: UI and Event Handling 70

71 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

72 Move a Message Charlie Abela CSA1019: UI and Event Handling 72

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

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics Topic 9: Swing Outline Swing = Java's GUI library Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 7: Expand moving shapes from Assignment 4 into game. "Programming

More information

Introduction to the JAVA UI classes Advanced HCI IAT351

Introduction to the JAVA UI classes Advanced HCI IAT351 Introduction to the JAVA UI classes Advanced HCI IAT351 Week 3 Lecture 1 17.09.2012 Lyn Bartram lyn@sfu.ca About JFC and Swing JFC Java TM Foundation Classes Encompass a group of features for constructing

More information

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Graphics programming COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Overview Aims To provide an overview of Swing and the AWT To show how to build

More information

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

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 5: Will be an open-ended Swing project. "Programming Contest"

More information

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!

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! Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Why are we studying Swing? 1. Useful & fun! 2. Good application of OOP techniques

More information

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline Sequential vs. Event-driven Programming Reacting to the user GUI Program Organization Let s digress briefly to examine the organization of our GUI programs We ll do this in stages, by examining three example

More information

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing. COSC User Interfaces Module 3 Sequential vs. Event-driven Programming Example Programs DemoLargestConsole.java DemoLargestGUI.java Demo programs will be available on the course web page. GUI Program Organization

More information

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

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 143 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

More information

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class. Q1. If you add a component to the CENTER of a border layout, which directions will the component stretch? A1. The component will stretch both horizontally and vertically. It will occupy the whole space

More information

GUI in Java TalentHome Solutions

GUI in Java TalentHome Solutions GUI in Java TalentHome Solutions AWT Stands for Abstract Window Toolkit API to develop GUI in java Has some predefined components Platform Dependent Heavy weight To use AWT, import java.awt.* Calculator

More information

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing CSEN401 Computer Programming Lab Topics: Graphical User Interface Window Interfaces using Swing Prof. Dr. Slim Abdennadher 22.3.2015 c S. Abdennadher 1 Swing c S. Abdennadher 2 AWT versus Swing Two basic

More information

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

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User CSE3461 Control Flow Paradigms: Reacting to the User Control Flow: Overview Definition of control flow: The sequence of execution of instructions in a program. Control flow is determined at run time by

More information

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7 PROGRAMMING DESIGN USING JAVA (ITT 303) Graphical User Interface Unit 7 Learning Objectives At the end of this unit students should be able to: Build graphical user interfaces Create and manipulate buttons,

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #19: November 4, 2015 1/14 Third Exam The third, Checkpoint Exam, will be on: Wednesday, November 11, 2:30 to 3:45 pm You will have 3 questions, out of 9,

More information

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs

More information

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI Statics and GUI Dynamics 2 Statics: what s drawn on the screen Components buttons, labels, lists, sliders, menus,... Containers: components that contain

More information

User interfaces and Swing

User interfaces and Swing User interfaces and Swing Overview, applets, drawing, action listening, layout managers. APIs: java.awt.*, javax.swing.*, classes names start with a J. Java Lectures 1 2 Applets public class Simple extends

More information

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs

More information

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

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 331 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

More information

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

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in Lab 4 D0010E Object-Oriented Programming and Design Lecture 9 Lab 4: You will implement a game that can be played over the Internet. The networking part has already been written. Among other things, the

More information

Chapter 1 GUI Applications

Chapter 1 GUI Applications Chapter 1 GUI Applications 1. GUI Applications So far we've seen GUI programs only in the context of Applets. But we can have GUI applications too. A GUI application will not have any of the security limitations

More information

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008 Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008 Announcements A3 is up, due Friday, Oct 10 Prelim 1 scheduled for Oct 16 if you have a conflict, let us know now 2 Interactive

More information

Graphic User Interfaces. - GUI concepts - Swing - AWT

Graphic User Interfaces. - GUI concepts - Swing - AWT Graphic User Interfaces - GUI concepts - Swing - AWT 1 What is GUI Graphic User Interfaces are used in programs to communicate more efficiently with computer users MacOS MS Windows X Windows etc 2 Considerations

More information

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

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread G51PGP Programming Paradigms Lecture 008 Inner classes, anonymous classes, Swing worker thread 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals

More information

Systems Programming Graphical User Interfaces

Systems Programming Graphical User Interfaces Systems Programming Graphical User Interfaces Julio Villena Román (LECTURER) CONTENTS ARE MOSTLY BASED ON THE WORK BY: José Jesús García Rueda Systems Programming GUIs based on Java

More information

BASICS OF GRAPHICAL APPS

BASICS OF GRAPHICAL APPS CSC 2014 Java Bootcamp Lecture 7 GUI Design BASICS OF GRAPHICAL APPS 2 Graphical Applications So far we ve focused on command-line applications, which interact with the user using simple text prompts In

More information

Graphical User Interfaces. Comp 152

Graphical User Interfaces. Comp 152 Graphical User Interfaces Comp 152 Procedural programming Execute line of code at a time Allowing for selection and repetition Call one function and then another. Can trace program execution on paper from

More information

11/6/15. Objec&ves. RouleQe. Assign 8: Understanding Code. Assign 8: Bug. Assignment 8 Ques&ons? PROGRAMMING PARADIGMS

11/6/15. Objec&ves. RouleQe. Assign 8: Understanding Code. Assign 8: Bug. Assignment 8 Ques&ons? PROGRAMMING PARADIGMS Objec&ves RouleQe Assign 8: Refactoring for Extensibility Programming Paradigms Introduc&on to GUIs in Java Ø Event handling Nov 6, 2015 Sprenkle - CSCI209 1 Nov 6, 2015 Sprenkle - CSCI209 2 Assign 8:

More information

Graphical User Interfaces (GUIs)

Graphical User Interfaces (GUIs) CMSC 132: Object-Oriented Programming II Graphical User Interfaces (GUIs) Department of Computer Science University of Maryland, College Park Model-View-Controller (MVC) Model for GUI programming (Xerox

More information

Lecture 5: Java Graphics

Lecture 5: Java Graphics Lecture 5: Java Graphics CS 62 Spring 2019 William Devanny & Alexandra Papoutsaki 1 New Unit Overview Graphical User Interfaces (GUI) Components, e.g., JButton, JTextField, JSlider, JChooser, Containers,

More information

CS 251 Intermediate Programming GUIs: Components and Layout

CS 251 Intermediate Programming GUIs: Components and Layout CS 251 Intermediate Programming GUIs: Components and Layout Brooke Chenoweth University of New Mexico Fall 2017 import javax. swing.*; Hello GUI public class HelloGUI extends JFrame { public HelloGUI ()

More information

The AWT Event Model 9

The AWT Event Model 9 The AWT Event Model 9 Course Map This module covers the event-based GUI user input mechanism. Getting Started The Java Programming Language Basics Identifiers, Keywords, and Types Expressions and Flow

More information

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs What is Widget Layout? Laying Out Components Positioning widgets in their container (typically a JPanel or a JFrame s content pane) Basic idea: each widget has a size and position Main problem: what if

More information

Basicsof. JavaGUI and SWING

Basicsof. JavaGUI and SWING Basicsof programming3 JavaGUI and SWING GUI basics Basics of programming 3 BME IIT, Goldschmidt Balázs 2 GUI basics Mostly window-based applications Typically based on widgets small parts (buttons, scrollbars,

More information

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120e) Programming Languages and Techniques (CIS120e) Lecture 29 Nov. 19, 2010 Swing I Event- driven programming Passive: ApplicaHon waits for an event to happen in the environment When an event occurs, the applicahon

More information

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Graphics. Lecture 18 COP 3252 Summer June 6, 2017 Graphics Lecture 18 COP 3252 Summer 2017 June 6, 2017 Graphics classes In the original version of Java, graphics components were in the AWT library (Abstract Windows Toolkit) Was okay for developing simple

More information

Java. GUI building with the AWT

Java. GUI building with the AWT Java GUI building with the AWT AWT (Abstract Window Toolkit) Present in all Java implementations Described in most Java textbooks Adequate for many applications Uses the controls defined by your OS therefore

More information

Laying Out Components. What is Widget Layout?

Laying Out Components. What is Widget Layout? Laying Out Components Interior Design for GUIs What is Widget Layout? Positioning widgets in their container (typically a JPanel or a JFrame s content pane) Basic idea: each widget has a size and position

More information

China Jiliang University Java. Programming in Java. Java Swing Programming. Java Web Applications, Helmut Dispert

China Jiliang University Java. Programming in Java. Java Swing Programming. Java Web Applications, Helmut Dispert Java Programming in Java Java Swing Programming Java Swing Design Goals The overall goal for the Swing project was: To build a set of extensible GUI components to enable developers to more rapidly develop

More information

Graphical User Interfaces 2

Graphical User Interfaces 2 Graphical User Interfaces 2 CSCI 136: Fundamentals CSCI 136: Fundamentals of Computer of Science Computer II Science Keith II Vertanen Keith Vertanen Copyright 2011 Extending JFrame Dialog boxes Overview

More information

CS 2113 Software Engineering

CS 2113 Software Engineering CS 2113 Software Engineering Java 5 - GUIs Import the code to intellij https://github.com/cs2113f18/template-j-5.git Professor Tim Wood - The George Washington University Class Hierarchies Abstract Classes

More information

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

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1 Java Swing based on slides by: Walter Milner Java Swing Walter Milner 2005: Slide 1 What is Swing? A group of 14 packages to do with the UI 451 classes as at 1.4 (!) Part of JFC Java Foundation Classes

More information

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling Handout 12 CS603 Object-Oriented Programming Fall 15 Page 1 of 12 Handout 14 Graphical User Interface (GUI) with Swing, Event Handling The Swing library (javax.swing.*) Contains classes that implement

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT-V TWO MARKS QUESTION & ANSWER 1. What is the difference between the Font and FontMetrics class? Font class is used to set or retrieve the screen fonts.the Font class maps the characters of the language

More information

CS11 Java. Fall Lecture 4

CS11 Java. Fall Lecture 4 CS11 Java Fall 2006-2007 Lecture 4 Today s Topics Interfaces The Swing API Event Handlers Inner Classes Arrays Java Interfaces Classes can only have one parent class No multiple inheritance in Java! By

More information

Unit 7: Event driven programming

Unit 7: Event driven programming Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Unit 7: Event driven programming 1 1. Introduction 2.

More information

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright GUI Basics Object Orientated Programming in Java Benjamin Kenwright Outline Essential Graphical User Interface (GUI) Concepts Libraries, Implementation, Mechanics,.. Abstract Windowing Toolkit (AWT) Java

More information

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

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation KF5008 Program Design & Development Lecture 1 Usability GUI Design and Implementation Types of Requirements Functional Requirements What the system does or is expected to do Non-functional Requirements

More information

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA Assignment No. 4 SD Module-1 Advanced JAVA R C (4) V T Total (10) Dated Sign Title: Transform the above system from command line system to GUI based application Problem Definition: Write a Java program

More information

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming Objectives: Last revised 1/15/10 1. To introduce the notion of a component and some basic Swing components (JLabel, JTextField, JTextArea,

More information

SD Module-1 Advanced JAVA. Assignment No. 4

SD Module-1 Advanced JAVA. Assignment No. 4 SD Module-1 Advanced JAVA Assignment No. 4 Title :- Transform the above system from command line system to GUI based application Problem Definition: Write a Java program with the help of GUI based Application

More information

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

encompass a group of features for building Graphical User Interfaces (GUI). Java GUI (intro) JFC Java Foundation Classes encompass a group of features for building Graphical User Interfaces (GUI). javax.swing.* used for building GUIs. Some basic functionality is already there

More information

Java: Graphical User Interfaces (GUI)

Java: Graphical User Interfaces (GUI) Chair of Software Engineering Carlo A. Furia, Marco Piccioni, and Bertrand Meyer Java: Graphical User Interfaces (GUI) With material from Christoph Angerer The essence of the Java Graphics API Application

More information

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

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class CHAPTER GRAPHICAL USER INTERFACES 10 Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11 10.1 Frame Windows Java provides classes to create graphical applications that can run on any major graphical

More information

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

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Rui Moreira Some useful links: http://java.sun.com/docs/books/tutorial/uiswing/toc.html http://www.unix.org.ua/orelly/java-ent/jfc/

More information

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Graphics and Events Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Draw shapes, text in various fonts, and colors. 2) Build

More information

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components CS112-Section2 Hakan Guldas Burcin Ozcan Meltem Kaya Muge Celiktas Notes of 6-8 May Graphics Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how

More information

Programming Mobile Devices J2SE GUI

Programming Mobile Devices J2SE GUI Programming Mobile Devices J2SE GUI University of Innsbruck WS 2009/2010 thomas.strang@sti2.at Graphical User Interface (GUI) Why is there more than one Java GUI toolkit? AWT write once, test everywhere

More information

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

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Frames, GUI and events Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Introduction to Swing The Java AWT (Abstract Window Toolkit)

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) 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

More information

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

Starting Out with Java: From Control Structures Through Objects Sixth Edition Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 12 A First Look at GUI Applications Chapter Topics 12.1 Introduction 12.2 Creating Windows 12.3 Equipping GUI Classes

More information

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn Java & Graphical User Interface II Wang Yang wyang AT njnet.edu.cn Outline Review of GUI (first part) What is Event Basic Elements of Event Programming Secret Weapon - Inner Class Full version of Event

More information

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC). The Abstract Windowing Toolkit Since Java was first released, its user interface facilities have been a significant weakness The Abstract Windowing Toolkit (AWT) was part of the JDK form the beginning,

More information

Part I: Learn Common Graphics Components

Part I: Learn Common Graphics Components OOP GUI Components and Event Handling Page 1 Objectives 1. Practice creating and using graphical components. 2. Practice adding Event Listeners to handle the events and do something. 3. Learn how to connect

More information

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

CSE 331. Event- driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 331 Event- driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT Lecturer: Michael Hotan slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer,

More information

GUI Programming: Swing and Event Handling

GUI Programming: Swing and Event Handling GUI Programming: Swing and Event Handling Sara Sprenkle 1 Announcements No class next Tuesday My Fourth of July present to you: No quiz! Assignment 3 due today Review Collections: List, Set, Map Inner

More information

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events Objectives Event Handling Animation Discussion of Roulette Assignment How easy/difficult to refactor for extensibility? Was it easier to add to your refactored code? Ø What would your refactored classes

More information

G51PRG: Introduction to Programming Second semester Applets and graphics

G51PRG: Introduction to Programming Second semester Applets and graphics G51PRG: Introduction to Programming Second semester Applets and graphics Natasha Alechina School of Computer Science & IT nza@cs.nott.ac.uk Previous two lectures AWT and Swing Creating components and putting

More information

Packages: Putting Classes Together

Packages: Putting Classes Together Packages: Putting Classes Together 1 Introduction 2 The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance) Extending interfaces The features in basic

More information

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI CBOP3203 Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI components like button, text input, scroll bar and others.

More information

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2, Java Mouse Actions C&G criteria: 5.2.1, 5.4.1, 5.4.2, 5.6.2. The events so far have depended on creating Objects and detecting when they receive the event. The position of the mouse on the screen can also

More information

(Incomplete) History of GUIs

(Incomplete) History of GUIs CMSC 433 Programming Language Technologies and Paradigms Spring 2004 Graphical User Interfaces April 20, 2004 (Incomplete) History of GUIs 1973: Xerox Alto 3-button mouse, bit-mapped display, windows 1981:

More information

Swing from A to Z Some Simple Components. Preface

Swing from A to Z Some Simple Components. Preface By Richard G. Baldwin baldwin.richard@iname.com Java Programming, Lecture Notes # 1005 July 31, 2000 Swing from A to Z Some Simple Components Preface Introduction Sample Program Interesting Code Fragments

More information

FirstSwingFrame.java Page 1 of 1

FirstSwingFrame.java Page 1 of 1 FirstSwingFrame.java Page 1 of 1 2: * A first example of using Swing. A JFrame is created with 3: * a label and buttons (which don t yet respond to events). 4: * 5: * @author Andrew Vardy 6: */ 7: import

More information

CSSE 220. Event Based Programming. Check out EventBasedProgramming from SVN

CSSE 220. Event Based Programming. Check out EventBasedProgramming from SVN CSSE 220 Event Based Programming Check out EventBasedProgramming from SVN Interfaces are contracts Interfaces - Review Any class that implements an interface MUST provide an implementation for all methods

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) 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

More information

Lecture 9. Lecture

Lecture 9. Lecture Layout Components MVC Design PaCern GUI Programming Observer Design PaCern D0010E Lecture 8 - Håkan Jonsson 1 Lecture 8 - Håkan Jonsson 2 Lecture 8 - Håkan Jonsson 3 1 1. GUI programming In the beginning,

More information

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages. 1 CS257 Computer Science I Kevin Sahr, PhD Lecture 14: Graphical User Interfaces Command-Line Applications 2 The programs we've explored thus far have been text-based applications A Java application is

More information

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

Part 3: Graphical User Interface (GUI) & Java Applets 1,QWURGXFWLRQWR-DYD3URJUDPPLQJ (( Part 3: Graphical User Interface (GUI) & Java Applets EE905-GUI 7RSLFV Creating a Window Panels Event Handling Swing GUI Components ƒ Layout Management ƒ Text Field ƒ

More information

Lecture 3: Java Graphics & Events

Lecture 3: Java Graphics & Events Lecture 3: Java Graphics & Events CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki Text Input Scanner class Constructor: myscanner = new Scanner(System.in); can use file instead of System.in new Scanner(new

More information

Computer Science 210: Data Structures. Intro to Java Graphics

Computer Science 210: Data Structures. Intro to Java Graphics Computer Science 210: Data Structures Intro to Java Graphics Summary Today GUIs in Java using Swing in-class: a Scribbler program READING: browse Java online Docs, Swing tutorials GUIs in Java Java comes

More information

Windows and Events. created originally by Brian Bailey

Windows and Events. created originally by Brian Bailey Windows and Events created originally by Brian Bailey Announcements Review next time Midterm next Friday UI Architecture Applications UI Builders and Runtimes Frameworks Toolkits Windowing System Operating

More information

Advanced Java Programming

Advanced Java Programming Advanced Java Programming Shmulik London Lecture #5 GUI Programming Part I AWT & Basics Advanced Java Programming / Shmulik London 2006 Interdisciplinary Center Herzeliza Israel 1 Agenda AWT & Swing AWT

More information

GUI Programming. Chapter. A Fresh Graduate s Guide to Software Development Tools and Technologies

GUI Programming. Chapter. A Fresh Graduate s Guide to Software Development Tools and Technologies A Fresh Graduate s Guide to Software Development Tools and Technologies Chapter 12 GUI Programming CHAPTER AUTHORS Ang Ming You Ching Sieh Yuan Francis Tam Pua Xuan Zhan Software Development Tools and

More information

What is Widget Layout? COSC 3461 User Interfaces. Hierarchical Widget Layout. Resizing a Window. Module 5 Laying Out Components

What is Widget Layout? COSC 3461 User Interfaces. Hierarchical Widget Layout. Resizing a Window. Module 5 Laying Out Components COSC User Interfaces Module 5 Laying Out Components What is Widget Layout? Positioning widgets in their container (typically a JPanel or a JFrame s content pane) Basic idea: each widget has a size and

More information

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

Graphical User Interfaces. Swing. Jose Jesus García Rueda Graphical User Interfaces. Swing Jose Jesus García Rueda Introduction What are the GUIs? Well known examples Basic concepts Graphical application. Containers. Actions. Events. Graphical elements: Menu

More information

Graphical User Interfaces 2

Graphical User Interfaces 2 Graphical User Interfaces 2 CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014 2011 Extending JFrame Dialog boxes Overview Ge

More information

2IS45 Programming

2IS45 Programming Course Website Assignment Goals 2IS45 Programming http://www.win.tue.nl/~wsinswan/programmeren_2is45/ Rectangles Learn to use existing Abstract Data Types based on their contract (class Rectangle in Rectangle.

More information

Class 16: The Swing Event Model

Class 16: The Swing Event Model Introduction to Computation and Problem Solving Class 16: The Swing Event Model Prof. Steven R. Lerman and Dr. V. Judson Harward 1 The Java Event Model Up until now, we have focused on GUI's to present

More information

BM214E Object Oriented Programming Lecture 13

BM214E Object Oriented Programming Lecture 13 BM214E Object Oriented Programming Lecture 13 Events To understand how events work in Java, we have to look closely at how we use GUIs. When you interact with a GUI, there are many events taking place

More information

CS11 Java. Fall Lecture 3

CS11 Java. Fall Lecture 3 CS11 Java Fall 2014-2015 Lecture 3 Today s Topics! Class inheritance! Abstract classes! Polymorphism! Introduction to Swing API and event-handling! Nested and inner classes Class Inheritance! A third of

More information

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

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University March 10, 2008 / Lecture 8 Outline Course Status Course Information & Schedule

More information

Java Programming Lecture 6

Java Programming Lecture 6 Java Programming Lecture 6 Alice E. Fischer Feb 15, 2013 Java Programming - L6... 1/32 Dialog Boxes Class Derivation The First Swing Programs: Snow and Moving The Second Swing Program: Smile Swing Components

More information

Graphical User Interfaces 2

Graphical User Interfaces 2 Graphical User Interfaces 2 CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Extending JFrame Dialog boxes Ge?ng user input Overview Displaying message or error Listening for

More information

PIC 20A GUI with swing

PIC 20A GUI with swing PIC 20A GUI with swing Ernest Ryu UCLA Mathematics Last edited: November 22, 2017 Hello swing Let s create a JFrame. import javax. swing.*; public class Test { public static void main ( String [] args

More information

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

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms. Java GUI Windows Events Drawing 1 Java GUI Toolkits Toolkit AWT Description Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

More information

Dr. Hikmat A. M. AbdelJaber

Dr. Hikmat A. M. AbdelJaber Dr. Hikmat A. M. AbdelJaber JWindow: is a window without a title bar or move controls. The program can move and resize it, but the user cannot. It has no border at all. It optionally has a parent JFrame.

More information

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo Widgets Overview Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo Widget Widget is a generic name for parts of an interface that have their own behavior: buttons, progress

More information

CSC207H: Software Design Lecture 11

CSC207H: Software Design Lecture 11 CSC207H: Software Design Lecture 11 Wael Aboelsaadat wael@cs.toronto.edu http://ccnet.utoronto.ca/20075/csc207h1y/ Office: BA 4261 Office hours: R 5-7 Acknowledgement: These slides are based on material

More information

GUI Components: Part 1

GUI Components: Part 1 1 2 11 GUI Components: Part 1 Do you think I can listen all day to such stuff? Lewis Carroll Even a minor event in the life of a child is an event of that child s world and thus a world event. Gaston Bachelard

More information