Java GUI Design: the Basics

Size: px
Start display at page:

Download "Java GUI Design: the Basics"

Transcription

1 Java GUI Design: the Basics Daniel Brady July 25, 2014 What is a GUI? A GUI is a graphical user interface, of course. What is a graphical user interface? A graphical user interface is simply a visual way of interacting with a computer. The desktop environment you are using right now to read this PDF is has GUI. The PDF viewer you are using to read this has a GUI. Basically, anything interactive that can be displayed on a screen is a GUI; technically, even a simple terminal or command prompt is a GUI. This document will introduce you to creating these types of applications in the Java programming language. How is designing a GUI dierent from designing a traditional application? GUIs are a dierent type of application from non-graphical programs, in that they do not 'ow' in the same ways. Traditional programs have a distinct beginning and end, a logical (if not always clear) path that can be (and is) followed once they are executed, and that path is dened by the code that was written. Graphical user interfaces, however, are event-driven programs and, as such, seemingly control themselves as opposed to following a predened path. This is true, in a sense: the code you write for a GUI is not designed to be executed in a predetermined order, but rather is intended to allow for almost arbitrary execution based on external (and sometimes, internal) events. It's like you're trying to speak to me, I know it. `Event-driven'? `Arbitrary execution'? I don't know what any of this means! Fear not, young programmer 1. Wisdom will come with experience. For now, let us start with the essentials. 1`Young' in the sense of knowledge, not age. 1

2 There are two types of GUI elements: 1 the essentials 1. Components: Components are elementary GUI entities (such as JButton, JLabel, and JTextField). 2. Containers: Containers (such as JFrame, JPanel, and JDialog) are used to hold components in a specic layout; a container can also contain other containers. For the purpose of creating graphical user interfaces in Java, we will be using the Java Swing and AWT graphics APIs. In a GUI program, every component must be held within a container. That container must be identied in some way, such that its add(jcomponent c) method can be called to add a component to itself. 1 JFrame frame = new JFrame ( " I yam a frame " ); 2 J P a n e l panel = new J P a n e l () ; 3 frame. add ( panel ); 4 JButton button = new JButton ( " I yam a button " ); 5 panel. add ( button ); 1.1 the frame The purpose of a GUI is to make it easier to interact with a computer. We've 2 found that visual aids tend to help this process. As such, GUIs are displayed on a screen. To separate one GUI from another, the graphical components of any given application 3 are placed inside a window, or frame. The frame of an application is the component of the GUI that typically contains the minimize-maximize-close buttons, as well as text displaying some title. Many frames often have menubars associated with them, with menus such as `File' and `Edit'. To create such a frame, you have two options: Create an instance of the javax.swing.jframe class Create a class which extends javax.swing.jframe, and create an instance of that class The rst option is best if you don't need to do anything to fancy or complicated and a generic JFrame will do what you want. 2 Not me. 3 In this document, `application' is used to refer to programs with GUIs, for the sake of brevity. It would be more accurate to say that an application has a GUI, but I don't want to. 2

3 1 // ---- Option \\ 2 JFrame frame = new JFrame ( " A title for the title bar." ); The second is better if you will be doing a lot of customization to your frame. 1 // ---- Option \\ 2 public c l a s s M y F r a m e extends J F r a m e { 3 //... 4 public s t a t i c void main ( S t r i n g [] args ) { 5 M y F r a m e frame = new M y F r a m e () ; 6 //... 7 } 8 } Once you have a frame, you can start thinking about setting up its behavior. Should the program exit when you close the frame? How big should the frame be? Should the user be able to resize it? These are questions you can provide answers to by modifying various attributes of your frame. Note: The order in which you set up the frame and its components can sometimes aect the behavior of your GUI. Unless you have a reason, you should apply frame settings last, after all of its components have been set up. 1 // ---- General frame settings \\ 2 frame. setdefaultcloseoperation ( J F r a m e. E X I T _ O N _ C L O S E ); 3 // exit the program when window is closed 4 frame. setsize ( 300, 400 ); 5 // set the width and height of the window 6 frame. setresizable ( f a l s e ); 7 // don ' t allow resizing once the frame has been created 8 frame. setvisible ( true ); 9 // make the frame visible ( and interactive!) to the user 3

4 If you are creating your own custom frame, you can congure these settings within the constructor of your frame instead, giving your frame a set of default behaviors should the user choose not to provide any. Once you've gotten your frame congured, it's time to start worrying about the content of that frame. 1.2 the canvas When a graphical component is rendered to the screen, it said to have been `drawn' or `painted' there. As such, the component onto which other components are `drawn' is referred to as a canvas. Another way to think about it is to consider the canvas a container, a place to hold and organize all the various components of your GUI. No matter how you visualize it, in Java GUIs the most commonly used such component is the javax.swing.jpanel. Every JFrame has exactly one container in which to organize its components. You can access this container via the getcontentpane method, and there are two ways you can handle it once you have it. 1 // ---- Option 1: treat as a generic java. awt. Container \\ 2 C o n t a i n e r contentcontainer = frame. getcontentpane ( ) ; 3 // retrieve and store the current content pane of the specified frame 4 // as a generic Container 5 // ---- Option 2: treat as a javax. swing. JPanel \\ 6 JPanel contentpanel = ( JPanel ) ^\ footnote { The \ texttt { getcontentpane } method of \ texttt { JFrame } actually returns a \ texttt { JPanel } as generic \ texttt { Container }, and so to treat it as a \ texttt { JPanel } it must be cast as such.}^ frame. getcontentpane ( ) ; 7 // retrieve and store the current content pane of the specified frame 8 // as a JPanel An alternative to dealing with the default content pane is to set the content pane to a JPanel of your choice via JFrame's setcontentpane method. 1 J P a n e l content = new J P a n e l () ; 2 frame. setcontentpane ( content ) ; Once you have your frame and canvas all set up, it's time to start adding the more exciting components of your GUI to your canvas! 1 content.add( somecomponent ) ; Keep in mind: the order in which you add components to the canvas matters, and the exact reasons why it matters are discussed later, in section 1.4 on layout managers. 4

5 1.3 the components The Java Swing and AWT packages provide many ready-made and reusable GUI components; the three that I will discuss here are some of the most commonly used: JButton, JLabel, and JTextField. There are three steps that are necessary to create and place a GUI component: 1. Declare the component, using a valid identier: 1 J B u t t o n button ; 2. Construct the component by invoking an appropriate constructor. 1 button = new JButton ( " I yam a button " ); 3. Identify the container (such as a JPanel) to hold the component. The container can then add the component onto itself via its add(jcomponent c) method. Every container has such a method. Take note that the container adds the component to itself: the component does not add the container as its parent. 1 J P a n e l container = new J P a n e l () ; 2 container. add( button ) ; If the component you are creating is never going to be used after creation (often this is the case when creating labels), then it is appropriate to simply add an anonymous instance of that component to a container instead of saving it away in a variable that will never be used again. 1 container. add ( new JLabel ( " WE ARE ANONYMOUS." ) ); the JButton A javax.swing.jbutton is a GUI component that triggers a certain pre-programmed action when clicked or otherwise activated by the user. The JButton has ve constructors, only four of which are commonly used. The no-arg constructor simply creates a blank button; another takes a String to use as display text; one takes an Icon to use instead of text; and yet another takes both a String and an Icon to use when displaying the button. 5

6 1 public J B u t t o n () ; 2 // Creates a button with no set text or icon. 3 public J B u t t o n ( S t r i n g text ); 4 // Creates a button with text. 5 public J B u t t o n ( Icon img ); 6 // Creates a button with an icon. 7 public J B u t t o n ( S t r i n g text, Icon img ); 8 // Creates a button with initial text and an icon. JButtons have various getters and setters associated with their commonly used attributes, such as gettext and seticon. But they can also be programmatically enabled or disabled, using the setenabled(boolean b) method the JLabel A javax.swing.jlabel provides a GUI component for rendering a short text string or an image, or both. Take note: System.out.print prints to the console, not to the screen of a GUI! JLabels are often used to label other components (such as a JTextField) or provide a text description. Similar to JButtons, there are many constructors for the JLabel. By default, JLabels are vertically centered in their display area, but you can specify where in the label's display are the label's contents are aligned by setting the vertical and horizontal alignment. You can also specify the position of the text relative to the image. 1 public J L a b e l () ; 2 // Creates a label with no image and with an empty 3 // string for the title. 4 public J L a b e l ( S t r i n g text ); 5 // Creates a label with the specified text. 6 public J L a b e l ( Icon img ); 7 // Creates a label with the specified image. 8 p u b l i c J L a b e l ( S t r i n g text, Icon img, i n t horizontalalignment ); 9 // Creates a label with the specified text, image, 10 // and horizontal alignment ( one of : LEFT, CENTER, RIGHT, LEADING or 11 // TRAILING, defined in javax. swing. SwingConstants ) The gettext and settext methods can be used to read and modify the Label's text. Similarly, the getalignment and setalignment methods can be used to retrieve and modify the alignment of the text. 6

7 1.3.3 the JTextField The javax.swing.jtextfield is a lightweight component that allows the editing of a single line of text. 4 Hitting the ENTER key while focused on a JTextField object will re an ActionEvent if the object is registered to any ActionListeners. 5 1 public J T e x t F i e l d ( i n t columns ); 2 // Constructs a new empty TextField with the specified number of 3 // columns. 4 public J T e x t F i e l d ( S t r i n g text ); 5 // Constructs a new TextField initialized with the specified text. 6 public J T e x t F i e l d ( S t r i n g text, i n t columns ); 7 // Constructs a new TextField initialized with the specified text 8 // and columns. As with other textual GUI components, the gettext and settext methods can be used to read and modify the text shown in a JTextField. Take note, however, that these methods work with Strings: if you are trying to insert any other data type, say a number, then that value must rst be converted to a String before calling gettext / settext. 1.4 layout managers TO BE WRITTEN 4 A JTextArea can be used if multiple lines of displayed and editable text are desired. 5 For information on and examples of using text elds see How to Use Text Fields in The Java Tutorial. 7

8 1.5 fully-worked example 1 import javax. swing.*; 2 3 public c l a s s M y s t e r y G u i extends J F r a m e { 4 // ---- Class and instance variables \\ 5 6 J P a n e l content ; 7 8 // ---- Constructors \\ 9 10 public M y s t e r y G u i () { 11 // Create and add the content pane. 12 content = new J P a n e l () ; 13 t h i s. setcontentpane ( content ); // Create and add the mystery labels. 16 content. add ( new J L a b e l ( "I am mystery," ) ); 17 content. add ( new JLabel ( " a wonderous sight to see " ) ); 18 content. add ( new JLabel ( " on a night like this." ) ); // General frame settings. 21 settitle ( " Haiku " ); 22 setdefaultcloseoperation ( J F r a m e. E X I T _ O N _ C L O S E ); 23 setsize ( 200, 110 ); 24 setlocationrelativeto ( n u l l ); 25 // a handy way of centering the frame on - screen 26 setvisible ( true ); 27 } // \\ 30 public s t a t i c void main ( S t r i n g [] args ) { 31 new M y s t e r y G u i () ; 32 } 33 } 8

9 2 event-driven programming The short story below can be used to illustrate the idea of event-driven programming. Event-driven programming is a programming paradigm in which the ow of the program is determined by eventsi.e., user actions such as mouse clicks and key presses. You're on a train: you don't know where that train is headed, but you know where you hope to end up. You arrive at the train station; stepping o of the train, you discover it is not your nal destination. You can choose get back on the same train, or try another line, but until you decide your journey has come to a halt. You decide get back on the train you just left, and it promptly whisks you away on the next leg of your journey. Strangely, the scenery you pass seems identical to the scenery you saw the last time you were on this train; indeed, looking ahead you can see the exact same train station you just left. Determined to be more prepared next time, you pull out your map and have a good look: there are so many routes that at rst it is hard to nd where you are. You arrive at the train station; stepping o of the train, you discover it is not your nal destination. You can choose get back on the same train, or try another line, but until you decide your journey has come to a halt. This time you decide to try a dierent line, and, crossing the station, you quickly board another train. Once again, as if it had been waiting for you, the train takes o as soon as you step onboard, nearly causing you to fall over. You manage to make it to your seat, and settle in for the ride. But just as you start to take notice of the wonderfully new scenery passing by, you feel the train start to slow: the next stop is coming up fast. You arrive at the train station; stepping o the train, you discover... Graphical user interfaces and other applications that are centered around performing certain actions in response to user input tend to follow the event-driven paradigm, and Java GUIs are no exception. In an event-driven application, there is generally a main loop that listens for events, triggering a piece of event-handling code when one of those events is detected. This behavior is unlike the more traditional procedural approach we are familiar with, in which programs are implemented in terms of explicit, sequential steps. Bits and pieces (the bodies of event-handlers and other methods) still execute sequentially, but the order in which these methods are called is determined by the order in which particular events occur. 9

10 Three objects are involved in the event-handling process: a source the listener(s) an event The source object (e.g. a JButton) interacts with the user. When triggered, it creates an event object. This event object is sent to all of the registered listener objects, and an appropriate event-handler method of the listener(s) is invoked upon it. Interested parties must rst register themselves with the source as active listeners of events before they can receive news of such things; without registration, the source has no idea that anybody is interested in the news it carries, and becomes sad and lonely. You can think of this relationship like that of a magazine or newspaper subscription: rst you subscribe to the distributor, and then anything they publish will get sent to you. This is a perfect example of the Observer design pattern, discussed in chapter 2 of Head First Design Patterns. When creating GUIs in Java, there are three major types of events 6 that you need to know how to handle: ActionEvents, KeyEvents, and MouseEvents. 2.1 ActionEvents and the ActionListener interface ActionEvents are versatile, meaningful events which indicate that a component-dened action has occurred. For example, if a JButton is pressed, or the user types ENTER in a JTextField, an ActionEvent is created and sent out to any one who is listening. Because of their behavior as a representative of a generic 'action' occurring, ActionEvent is the most commonly extended event class when creating your own types of events. Objects which are interested in listening and handling ActionEvents must implement the ActionListener interface. 1 // ---- ActionListener interface \\ 2 public i n t e r f a c e A c t i o n L i s t e n e r { 3 p u b l i c void actionperformed ( A c t i o n E v e n t e ) ; 4 // Invoked when an action occurs. 5 } Furthermore, these listeners must be registered with the source (of the desired events) via the source's addactionlistener method. 6 Located in the java.awt.event package 10

11 There are two common ways of creating and registering event-listeners: 1. add an instance of the EventListener class itself 2. add an instance of a user-dened EventListener class 1 // ---- Option 1: generic listener \\ 2 source. addactionlistener ( new A c t i o n L i s t e n e r () { 7 4 p u b l i c void actionperformed ( A c t i o n E v e n t e ) { 5 // Handle the action. 6 //... 7 } 8 } ) ; 9 10 // ---- Option 2: custom listener \\ 11 source. addactionlistener ( new F r A ct i o n L i st e n e r () ) ; Here's an example of a simple listener which keeps track of and reports how many times it has received an ActionEvent: 1 import java. awt. event. A c t i o n E v e n t ; 2 import java. awt. event. A c t i o n L i s t e n e r ; 3 public c l a s s A c t i o n T r a c k e r implements A c t i o n L i s t e n e r { 4 // ---- Class and instance variables \\ 5 6 i n t count ; // initialized to 0 by default 7 8 // ---- Utility methods \\ 9 10 /* * 11 * Records and reports how many times an action has occurred. 12 */ Override 14 p u b l i c void actionperformed ( A c t i o n E v e n t e ) { 15 count ++; 16 System. out. println ( count + ( count == 1? 17 " action has occurred." 18 : " actions have occurred." ) 19 ); 20 } 21 } 7 An annotation used to convey the intention of the programmer to override an inherited method. See this tutorial on Java Annotations for more details. 11

12 2.2 KeyEvents and the KeyListener interface A KeyEvent is an event that is red when a keystroke occurs in a component. This event is generated by a component when a key is pressed, released, or typed. Following the Observer pattern, the event is then passed to every KeyListener object registered to receive such events, using the component's addkeylistener method. 1 // ---- KeyListener interface \\ 2 public i n t e r f a c e K e y L i s t e n e r { 3 public void keypressed ( K e y E v e n t e ) ; 4 // Invoked when a key has been pressed. 5 public void keyreleased ( K e y E v e n t e ) ; 6 // Invoked when a key has been released. 7 public void keytyped ( K e y E v e n t e ) ; 8 // Invoked when a key has been typed. 9 } There is an important dierence between the events generated by keypressed / keyreleased methods and the keytyped method, outlined in detail in the documentation on KeyEvents. To summarize, `key typed' events are not red simply when the component registers a backto-back press-and-release (like the mouseclicked method described below does); rather, a `key typed' event will typically occur when a valid Unicode character is entered. The dierence here is subtle, but it is there: many valid characters are entered via a series of key-presses (`Shift' + `a', for example), and therefore deserve to be recognized by a single event. As a result, `key pressed' and `key released' events are low-level events, meaning they depend on the particular platform and keyboard layout used to generate the event and are therefore the only way to nd out about keys that don't generate character input (e.g. `Shift', `Ctrl', etc.). `Key typed' events are higher-level, platform and keyboard independent, but cannot detect such key-presses. Below is an excellent example that highlights the dierence between these three events. For this EventListener, I have provided an example of a main method in which the listener might be used. This is a complete GUI. 12

13 1 import javax. swing.*; 2 import java. awt.*; 3 import java. awt. event.*; 4 public class K e y T r a c k e r implements K e y L i s t e n e r { 5 6 // ---- Utility methods \\ 7 9 public void keypressed ( K e y E v e n t e ) { 10 System. out. println ( " KEY PRESSED EVENT \ n =================\ n" 11 + "\ tkey description : " 12 + KeyEvent. getkeytext ( e. getkeycode () ) 13 + "\ n\ tkey character : " 14 + e. getkeychar () 15 ); 16 } public void keyreleased ( K e y E v e n t e ) { 20 System. out. println ( " KEY RELEASED EVENT \ n ==================\ n" 21 + "\ tkey description : " 22 + KeyEvent. getkeytext ( e. getkeycode () ) 23 + "\ n\ tkey character : " 24 + e. getkeychar () 25 ); 26 S y s t e m. out. println () ; 27 S y s t e m. out. println () ; 28 } public void keytyped ( K e y E v e n t e ) { 32 System. out. println ( " KEY TYPED EVENT \ n ===============\ n" 33 // The getkeycode () method of a key - typed event 34 // always returns VK_UNDEFINED "\ tkey description : " 36 + KeyEvent. getkeytext ( e. getkeycode () ) 37 + "\ n\ tkey character : " 38 + e. getkeychar () 39 ); 40 } public static void main ( S t r i n g [] args ) { 43 JFrame frame = new JFrame ( " KEY TEST " ); 44 JPanel content = new JPanel () ; 45 frame. setcontentpane ( content ); JTextField tfinput = new JTextField ( 9 ); // space for >= 9 chars 48 tfinput. addkeylistener ( new KeyTracker () ); 49 content. add ( tfinput ); frame. setdefaultcloseoperation ( JFrame. EXIT_ON_CLOSE ); 52 frame. setsize ( 200, 75 ); 53 frame. setlocationrelativeto ( null ); // center frame on - screen 54 frame. setvisible ( true ); 55 } 56 } 13

14 2.3 MouseEvents and the MouseListener interface MouseEvents are generated to indicate that a mouse action 8 has occurred in a component; this is considered to be the case if and only if the mouse cursor is over a visible (unobscured by another component) part of the component's bounds when the action happens. And just like with all events, a generated MouseEvent is sent to any listeners that have registered with the source as interested MouseListeners. 1 // ---- MouseListener interface \\ 2 public i n t e r f a c e M o u s e L i s t e n e r { 3 p u b l i c void mousepressed ( M o u s e E v e n t evt ) ; 4 // Invoked when the mouse button has been pressed 5 p u b l i c void mousereleased ( M o u s e E v e n t evt ) ; 6 // Invoked when the mouse button has been released 7 p u b l i c void mouseclicked ( M o u s e E v e n t evt ) ; 8 // Invoked when the mouse button has been clicked ( pressed and 9 // released ) 10 p u b l i c void mouseentered ( M o u s e E v e n t evt ) ; 11 // Invoked when mouse cursor has entered the unobscured bounds 12 // of a component 13 p u b l i c void mouseexited ( M o u s e E v e n t evt ) ; 14 // Invoked when mouse cursor has exited the unobscured bounds 15 // of a component 16 } The next example is a long one, as a direct result of the amount of methods being implemented, but hopefully it is quite clear. Once again, the example is a fully-working GUI, and can be executed directly. 8 A closely related (and, in fact, subclass) of the MouseEvent is the MouseWheelEvent, generated in response to scrolling the wheel of the mouse. It has its own EventListener, the MouseWheelListener. 14

15 1 import javax. swing.*; 2 import java. awt.*; 3 import java. awt. event.*; 4 public class M o u s e T r a c k e r implements M o u s e L i s t e n e r { 5 6 // ---- Utility methods \\ 7 9 public void mousepressed ( M o u s e E v e n t e ) { 10 S t r i n g button ; 11 switch ( e. getbutton () ) { 12 case MouseEvent. BUTTON1 : 13 button = " LEFT "; 14 break; 15 case MouseEvent. BUTTON2 : 16 button = " MIDDLE "; 17 break; 18 case MouseEvent. BUTTON3 : 19 button = " RIGHT "; 20 break; 21 default : 22 button = ""; 23 break; 24 } 25 System. out. println ( " The " + button + " mouse button has been \ n" 26 + "\ t( relative to the source ): " 27 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 28 + "\ t( relative to the screen ): " 29 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 30 ); 31 } public void mousereleased ( M o u s e E v e n t e ) { 36 S t r i n g button ; 37 switch ( e. getbutton () ) { 38 case MouseEvent. NOBUTTON : 39 button = " invisible "; 40 break; 41 case MouseEvent. BUTTON1 : 42 button = " LEFT "; 43 break; 44 case MouseEvent. BUTTON2 : 45 button = " MIDDLE "; 46 break; 47 case MouseEvent. BUTTON3 : 48 button = " RIGHT "; 49 break; 50 default : 51 button = ""; 52 break; 53 } 54 System. out. println ( " The " + button + " mouse button has been \ n" 55 + "\ t( relative to the source ): " 56 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 57 + "\ t( relative to the screen ): " 58 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 59 ); 60 }

16 63 65 public void mouseclicked ( M o u s e E v e n t e ) { 66 S t r i n g button ; 67 switch ( e. getbutton () ) { 68 case MouseEvent. NOBUTTON : 69 button = " invisible "; 70 break; 71 case MouseEvent. BUTTON1 : 72 button = " LEFT "; 73 break; 74 case MouseEvent. BUTTON2 : 75 button = " MIDDLE "; 76 break; 77 case MouseEvent. BUTTON3 : 78 button = " RIGHT "; 79 break; 80 default : 81 button = ""; 82 break; 83 } 84 System. out. println ( " The " + button + " mouse button has been \ n" 85 + "\ t( relative to the source ): " 86 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 87 + "\ t( relative to the screen ): " 88 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 89 ); 90 } public void mouseentered ( M o u s e E v e n t e ) { 94 System. out. println ( " Mouse ENTERED the \ n" 95 + "\ t( relative to the source ): " 96 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 97 + "\ t( relative to the screen ): " 98 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 99 ); 100 } public void mouseexited ( M o u s e E v e n t e ) { 104 System. out. println ( " Mouse EXITED the \ n" "\ t( relative to the source ): " "[" + e. getx () + ", " + e. gety () + " ]\ n" "\ t( relative to the screen ): " "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 109 ); 110 } public static void main ( S t r i n g [] args ) { 113 JFrame frame = new JFrame ( " Key test " ); 114 JPanel content = new JPanel () ; 115 frame. setcontentpane ( content ); content. addmouselistener ( new MouseTracker () ); frame. setdefaultcloseoperation ( JFrame. EXIT_ON_CLOSE ); 120 frame. setsize ( 100, 100 ); 121 frame. setlocationrelativeto ( null ); 122 frame. setvisible ( true ); 123 } 124 } 16

17 and the MouseMotionListener interface Very closely related to the MouseListener interface, the MouseMotionListener interface responds to MouseEvents that are generated due to mouse motion or movement. As before, a MouseMotionListener must be registered with a source via the addmousemotionlistener method in order to receive interesting events. 1 // ---- MouseMotionListener interface \\ 2 public interface M o u s e M o t i o n L i s t e n e r { 3 public void mousedragged ( M o u s e E v e n t e ) ; 4 // Invoked when a mouse button is pressed on a component and then 5 // dragged. 6 public void mousemoved ( M o u s e E v e n t e ) ; 7 // Invoked when the mouse cursor has been moved onto a component 8 // but no buttons have been pushed. 9 } Here is an example that is very similar to the previous one, but provides a GUI that only cares about the motion of the mouse and not its clicks. 1 import javax. swing.*; 2 import java. awt.*; 3 import java. awt. event.*; 4 public class M o u s e M o t i o n T r a c k e r implements M o u s e M o t i o n L i s t e n e r { 5 6 // ---- Utility methods \\ 8 public void mousedragged ( M o u s e E v e n t e ) { 9 System. out. println ( " The mouse is being DRAGGED, \ n" 10 + "\ t( relative to the source ): " 11 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 12 + "\ t( relative to the screen ): " 13 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 14 ); 15 } public void mousemoved ( M o u s e E v e n t e ) { 19 System. out. println ( " The mouse is MOVING, \ n" 20 + "\ t( relative to the source ): " 21 + "[" + e. getx () + ", " + e. gety () + " ]\ n" 22 + "\ t( relative to the screen ): " 23 + "[" + e. getxonscreen () + ", " + e. getyonscreen () + " ]\ n" 24 ); 25 } public static void main ( S t r i n g [] args ) { 28 JFrame frame = new JFrame ( " Key test " ); 29 JPanel content = new JPanel () ; 30 frame. setcontentpane ( content ); content. addmousemotionlistener ( new MouseMotionTracker () ); frame. setdefaultcloseoperation ( JFrame. EXIT_ON_CLOSE ); 35 frame. setsize ( 100, 100 ); 36 frame. setlocationrelativeto ( null ); 37 frame. setvisible ( true ); 38 } 39 } 17

18 3 coming up next... I hope you nd this document to be as useful as I intend it to be. Below, you will nd various class diagrams of the Java Swing API, illustrating how they all t together. My next document will provide step-by-step instructions in the creation of Stage 1 of our Tetris game. Happy coding! ~1)aniel 13rady 18

19 19

CS 251 Intermediate Programming GUIs: Event Listeners

CS 251 Intermediate Programming GUIs: Event Listeners CS 251 Intermediate Programming GUIs: Event Listeners Brooke Chenoweth University of New Mexico Fall 2017 What is an Event Listener? A small class that implements a particular listener interface. Listener

More information

Event Driven Programming

Event Driven Programming Event Driven Programming 1. Objectives... 2 2. Definitions... 2 3. Event-Driven Style of Programming... 2 4. Event Polling Model... 3 5. Java's Event Delegation Model... 5 6. How to Implement an Event

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

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

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

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is INDEX Event Handling. Key Event. Methods Of Key Event. Example Of Key Event. Mouse Event. Method Of Mouse Event. Mouse Motion Listener. Example of Mouse Event. Event Handling One of the key concept in

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

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

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

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

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

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

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

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

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS Glossary of Terms 2-4 Step by Step Instructions 4-7 HWApp 8 HWFrame 9 Never trust a computer

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

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

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

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

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

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

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

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */ 25 4 GUI GUI GUI 4.1 4.1.1 MouseTest.java /* 1 */ public class MouseTest extends JApplet implements MouseListener /* 2 */ { int x=50, y=20; addmouselistener(this); /* 3 */ super.paint(g); /* 4 */ g.drawstring("hello

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

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

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Spring 2017 GUI Event-Driven Programming 1 The plan User events and callbacks Event objects Event listeners Registering listeners to handle events Anonymous

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

10/16/2008. CSG 170 Round 5. Prof. Timothy Bickmore. User Analysis Task Analysis (6) Problem Scenarios (3)

10/16/2008. CSG 170 Round 5. Prof. Timothy Bickmore. User Analysis Task Analysis (6) Problem Scenarios (3) Human-Computer Interaction CSG 170 Round 5 Prof. Timothy Bickmore T2: Requirements Analysis Review User Analysis Task Analysis (6) Problem Scenarios (3) 1 T2 Review Requirements Analysis Who is the user?

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

COMPSCI 230. Software Design and Construction. Swing

COMPSCI 230. Software Design and Construction. Swing COMPSCI 230 Software Design and Construction Swing 1 2013-04-17 Recap: SWING DESIGN PRINCIPLES 1. GUI is built as containment hierarchy of widgets (i.e. the parent-child nesting relation between them)

More information

AP CS Unit 11: Graphics and Events

AP CS Unit 11: Graphics and Events AP CS Unit 11: Graphics and Events This packet shows how to create programs with a graphical interface in a way that is consistent with the approach used in the Elevens program. Copy the following two

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

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI 51 6!! GUI(Graphical User Interface) java.awt javax.swing (component) GUI... (container) (listener)... MouseListener, ActionLister (adapter)... MouseAdapter, ActionAdapter 6.1 GUI(Graphics User Interface

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

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

Lecture 19 GUI Events

Lecture 19 GUI Events CSE 331 Software Design and Implementation Lecture 19 GUI Events The plan User events and callbacks Event objects Event listeners Registering listeners to handle events Anonymous inner classes Proper interaction

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

Dr. Hikmat A. M. AbdelJaber

Dr. Hikmat A. M. AbdelJaber Dr. Hikmat A. M. AbdelJaber GUI are event driven (i.e. when user interacts with a GUI component, the interaction (event) derives the program to perform a task). Event: click button, type in text field,

More information

GUI Software Architecture

GUI Software Architecture GUI Software Architecture P2: Requirements Analysis User Analysis Task Analysis Problem Scenarios Usability Criteria Scenario Your engineers just developed a new desktop computer. They give you the following

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

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

Module 4 Multi threaded Programming, Event Handling. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Module 4 Multi threaded Programming, Event Handling. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Module 4 Multi threaded Programming, Event Handling OOC 4 th Sem, B Div 2017-18 Prof. Mouna M. Naravani Event Handling Complete Reference 7 th ed. Chapter No. 22 Event Handling Any program that uses a

More information

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

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau List of Slides 1 Title 2 Chapter 13: Graphical user interfaces 3 Chapter aims 4 Section 2: Example:Hello world with a GUI 5 Aim 6 Hello world with a GUI 7 Hello world with a GUI 8 Package: java.awt and

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

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

AP Computer Science Unit 13. Still More Graphics and Animation.

AP Computer Science Unit 13. Still More Graphics and Animation. AP Computer Science Unit 13. Still More Graphics and Animation. In this unit you ll learn about the following: Mouse Motion Listener Suggestions for designing better graphical programs Simple game with

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

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

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University Java Swing Recitation 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University Announcements Project 8 is out Milestone due on Dec 3rd, 10:00 pm Final due on Dec 10th, 10:00 pm No classes,

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

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

CSE 331 Software Design and Implementation. Lecture 19 GUI Events CSE 331 Software Design and Implementation Lecture 19 GUI Events Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 7 due Thursday 8/9 Homework 8 due Thursday 8/9 HW8 has a regression testing

More information

GUI Event Handlers (Part I)

GUI Event Handlers (Part I) GUI Event Handlers (Part I) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda General event

More information

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world Visit us on the

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

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

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

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons CompSci 125 Lecture 17 GUI: Graphics, Check Boxes, Radio Buttons Announcements GUI Review Review: Inheritance Subclass is a Parent class Includes parent s features May Extend May Modify extends! Parent

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

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

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1 Datenbank-Praktikum Universität zu Lübeck Sommersemester 2006 Lecture: Swing Ho Ngoc Duc 1 Learning objectives GUI applications Font, Color, Image Running Applets as applications Swing Components q q Text

More information

3 Combining Widgets to create Graphical User Interfaces

3 Combining Widgets to create Graphical User Interfaces (Graphical User Interfaces - 41) 3 Combining Widgets to create Graphical User Interfaces 3.1 The Ressource Concept Goal: How to compose widgets to create complete user interfaces Problem: Composition has

More information

Java Interfaces Part 1 - Events Version 1.1

Java Interfaces Part 1 - Events Version 1.1 Java Interfaces Part 1 - Events Version 1.1 By Dr. Nicholas Duchon July 22, 2007 Page 1 Overview Philosophy Large Scale Java Language Structures Abstract classes Declarations Extending a abstract classes

More information

Graphics User Defined Forms, Part I

Graphics User Defined Forms, Part I Graphics User Defined Forms, Part I Quick Start Compile step once always mkdir labs javac PropertyTax5.java cd labs mkdir 5 Execute step cd 5 java PropertyTax5 cp /samples/csc/156/labs/5/*. cp PropertyTax1.java

More information

UI Software Organization

UI Software Organization UI Software Organization The user interface From previous class: Generally want to think of the UI as only one component of the system Deals with the user Separate from the functional core (AKA, the app

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

Programming graphics

Programming graphics Programming graphics Need a window javax.swing.jframe Several essential steps to use (necessary plumbing ): Set the size width and height in pixels Set a title (optional), and a close operation Make it

More information

GUI Forms and Events, Part II

GUI Forms and Events, Part II GUI Forms and Events, Part II Quick Start Compile step once always mkdir labs javac PropertyTax6.java cd labs Execute step mkdir 6 java PropertyTax6 cd 6 cp../5/propertytax5.java PropertyTax6.java Submit

More information

Graphical User Interface

Graphical User Interface Lecture 10 Graphical User Interface An introduction Sahand Sadjadee sahand.sadjadee@liu.se Programming Fundamentals 725G61 http://www.ida.liu.se/~725g61/ Department of Computer and Information Science

More information

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4. 1 - What if the main method is declared as private? 1. The program does not compile 2. The program compiles but does not run 3. The program compiles and runs properly ( From Lectuer # 2) 4. The program

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

CS Exam 1 Review Suggestions

CS Exam 1 Review Suggestions CS 235 - Fall 2015 - Exam 1 Review Suggestions p. 1 last modified: 2015-09-30 CS 235 - Exam 1 Review Suggestions You are responsible for material covered in class sessions, lab exercises, and homeworks;

More information

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science mluckner@mini.pw.edu.pl http://www.mini.pw.edu.pl/~lucknerm } Abstract Window Toolkit Delegates creation and

More information

Assignment 1. Application Development

Assignment 1. Application Development Application Development Assignment 1 Content Application Development Day 1 Lecture The lecture provides an introduction to programming, the concept of classes and objects in Java and the Eclipse development

More information

GUI Event Handlers (Part II)

GUI Event Handlers (Part II) GUI Event Handlers (Part II) 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda Listener

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

Lecture (06) Java Forms

Lecture (06) Java Forms Lecture (06) Java Forms Dr. Ahmed ElShafee 1 Dr. Ahmed ElShafee, Fundamentals of Programming I, Introduction You don t have to output everything to a terminal window in Java. In this lecture, you ll be

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

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

14.2 Java s New Nimbus Look-and-Feel 551 Sample GUI: The SwingSet3 Demo Application As an example of a GUI, consider Fig. 14.1, which shows the SwingS 550 Chapter 14 GUI Components: Part 1 14.1 Introduction 14.2 Java s New Nimbus Look-and-Feel 14.3 Simple GUI-Based Input/Output with JOptionPane 14.4 Overview of Swing Components 14.5 Displaying Text and

More information

Example: Building a Java GUI

Example: Building a Java GUI Steven Zeil October 25, 2013 Contents 1 Develop the Model 2 2 Develop the layout of those elements 3 3 Add listeners to the elements 9 4 Implement custom drawing 12 1 The StringArt Program To illustrate

More information

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR DEMYSTIFYING PROGRAMMING: CHAPTER FOUR Chapter Four: ACTION EVENT MODEL 1 Objectives 1 4.1 Additional GUI components 1 JLabel 1 JTextField 1 4.2 Inductive Pause 1 4.4 Events and Interaction 3 Establish

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

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

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

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

Input (part 2: input models)

Input (part 2: input models) Input (part 2: input models) Dealing with diversity Saw lots of diversity in devices actual details of devices (e.g., device drivers) is a real pain how do we deal with the diversity? Need a model (abstraction)

More information

AP CS Unit 12: Drawing and Mouse Events

AP CS Unit 12: Drawing and Mouse Events AP CS Unit 12: Drawing and Mouse Events A JPanel object can be used as a container for other objects. It can also be used as an object that we can draw on. The first example demonstrates how to do that.

More information

Summary. Section 14.1 Introduction. Section 14.2 Java s New Nimbus Look-and-Feel. 618 Chapter 14 GUI Components: Part 1

Summary. Section 14.1 Introduction. Section 14.2 Java s New Nimbus Look-and-Feel. 618 Chapter 14 GUI Components: Part 1 618 Chapter 14 GUI Components: Part 1 erence to a JScrollPane, the program can use JScrollPane methods sethorizontal- ScrollBarPolicy and setverticalscrollbarpolicy to change the scrollbar policies at

More information

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

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords Goals By the end of this lesson, you should: Lecture 7 More GUI programming 1. Be able to write Java s with JTextField, JList, JCheckBox and JRadioButton components 2. Be able to implement a ButtonGroup

More information

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1 DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1 Objectives 1 6.1 Methods 1 void or return 1 Parameters 1 Invocation 1 Pass by value 1 6.2 GUI 2 JButton 2 6.3 Patterns

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 IDE Programming-I

Java IDE Programming-I Java IDE Programming-I Graphical User Interface : is an interface that uses pictures and other graphic entities along with text, to interact with user. User can interact with GUI using mouse click/ or

More information

PIC 20A Anonymous classes, Lambda Expressions, and Functional Programming

PIC 20A Anonymous classes, Lambda Expressions, and Functional Programming PIC 20A Anonymous classes, Lambda Expressions, and Functional Programming Ernest Ryu UCLA Mathematics Last edited: December 8, 2017 Introductory example When you write an ActionListener for a GUI, you

More information

12/22/11. Copyright by Pearson Education, Inc. All Rights Reserved.

12/22/11. Copyright by Pearson Education, Inc. All Rights Reserved. } Radio buttons (declared with class JRadioButton) are similar to checkboxes in that they have two states selected and not selected (also called deselected). } Radio buttons normally appear as a group

More information

Example: Building a Java GUI

Example: Building a Java GUI Steven Zeil October 25, 2013 Contents 1 Develop the Model 3 2 Develop the layout of those elements 4 3 Add listeners to the elements 12 4 Implement custom drawing 15 1 The StringArt Program To illustrate

More information

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014 Introduction to GUIs Principles of Software Construction: Objects, Design, and Concurrency Jonathan Aldrich and Charlie Garrod Fall 2014 Slides copyright 2014 by Jonathan Aldrich, Charlie Garrod, Christian

More information

MIT AITI Swing Event Model Lecture 17

MIT AITI Swing Event Model Lecture 17 MIT AITI 2004 Swing Event Model Lecture 17 The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the user. But how do GUIs interact with users? How do applications

More information

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology: Inheritance 1 Inheritance One class inherits from another if it describes a specialized subset of objects Terminology: the class that inherits is called a child class or subclass the class that is inherited

More information

Graphical interfaces & event-driven programming

Graphical interfaces & event-driven programming Graphical interfaces & event-driven programming Lecture 12 of TDA 540 (Objektorienterad Programmering) Carlo A. Furia Alex Gerdes Chalmers University of Technology Gothenburg University Fall 2017 Pop quiz!

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

Come & Join Us at VUSTUDENTS.net

Come & Join Us at VUSTUDENTS.net Come & Join Us at VUSTUDENTS.net For Assignment Solution, GDB, Online Quizzes, Helping Study material, Past Solved Papers, Solved MCQs, Current Papers, E-Books & more. Go to http://www.vustudents.net and

More information