The Abstract Window Toolkit

Size: px
Start display at page:

Download "The Abstract Window Toolkit"

Transcription

1 Chapter 12 The Abstract Window Toolkit 1

2 12.1 Overview Java s Abstract Window Toolkit provides classes and other tools for building programs that have a graphical user interface. The term Abstract refers to the AWT s ability to run on multiple platforms. Building a GUI involves creating abstract components such as buttons and windows, which are then mapped to concrete components for a specific platform. 2

3 Swing Java has a newer library for building graphical user interfaces, known as Swing. Swing is more powerful and sophisticated than the AWT. Swing is built around the existing AWT, so it helps to understand the AWT first. Swing is similar enough to the AWT that it s relatively easy to switch if the need arises. Many Swing classes correspond to AWT classes. For example, Swing s JButton class corresponds to the AWT s Button class. 3

4 Creating a Graphical User Interface GUI programming in Java is based on three concepts: Components. A component is an object that the user can see on the screen and in most cases interact with. Containers. A container is a component that can hold other components. Events. An event is an action triggered by the user, such as a key press or mouse click. Designing a graphical user interface involves creating components, putting them into containers, and arranging for the program to respond to events. 4

5 Creating a Graphical User Interface Components are objects, so they re created by invoking a constructor. A button would be created by using a constructor belonging to the Button class. The most commonly used constructor has one argument (the button s label): Button b = new Button("Testing"); For a component to be visible, it must be added to a container (typically a frame) by the add method. 5

6 Creating a Graphical User Interface To detect when an event occurs, a special listener object can be attached to a component. When the user performs an action that involves the component, a method belonging to the listener object will be called automatically. 6

7 12.2 Frames In Java terminology, a frame is a window with a title and a border. A frame may also have a menu bar. Frames play an important role in the AWT because a GUI program normally displays a frame when it s executed. 7

8 The Frame Class Frames are created using one of the constructors in the Frame class. One constructor takes a single argument (the title to be displayed at the top of the frame): Frame f = new Frame("Title goes here"); Although the Frame object now exists, it s not visible on the screen. Before making the frame visible, a method should be called to set the size of the frame. If desired, the frame s location can also be specified. 8

9 Frame Methods Many methods used with Frame objects are inherited from Window (Frame s superclass) or from Component (Window s superclass). The setsize method sets the width and height of a frame: f.setsize(width, height); If a program fails to call setsize or pack before displaying a frame, it will assume a default size. 9

10 Frame Methods The size of a frame can change during the execution of a program. The getsize method returns a frame s current width and height: Dimension framesize = f.getsize(); framesize.width will contain f s width. framesize.height will contain f s height. 10

11 Frame Methods The setvisible method controls whether or not a frame is currently visible on the screen. Calling setvisible with true as the argument makes a frame visible: f.setvisible(true); Calling it with false as the argument makes the frame disappear from the screen: f.setvisible(false); The Frame object still exists; it can be made to reappear later by calling setvisible again. 11

12 Creating a Frame The FrameTest program creates a Frame object and displays it on the screen. This program illustrates three key steps: 1. Using the Frame constructor to create a frame. 2. Setting the size of the frame. 3. Displaying the frame on the screen. 12

13 FrameTest.java // Displays a frame on the screen. // WARNING: Frame cannot be closed. import java.awt.*; public class FrameTest { public static void main(string[] args) { Frame f = new Frame("Frame Test"); f.setsize(150, 100); f.setvisible(true); } } 13

14 Creating a Frame Frame created by the FrameTest program: As with the other AWT components, the appearance of a frame depends on the platform. 14

15 Creating a Frame Clicking on the Close button has no effect, because there s no action associated with that button. The frame will have be closed the hard way, by killing the program. In Windows, click on the DOS window from which the program was launched, hold down the Ctrl key, and press the letter C. 15

16 Setting the Location of a Frame By default, all windows (including frames) are displayed in the upper-left corner of the screen, which has coordinates (0, 0). The setlocation method can be used to specify a different location: f.setlocation(50, 75); To find the current location of a frame, call getlocation: Point framelocation = f.getlocation(); The coordinates of f s upper-left corner will be stored in framelocation.x and framelocation.y. 16

17 Adding Components to a Frame The Frame class is rarely used to create objects directly. Instead, it s customary to define a subclass of Frame and then create an instance of the subclass. This strategy makes it possible to tailor the subclass. In particular, the constructor for the subclass can put components into the frame. 17

18 Adding Components to a Frame To add a component to a frame (or any kind of container), the add method is used. add belongs to the Container class, so it s inherited by Frame and the other container classes. An example of adding a button to a frame: Button b = new Button("Testing"); add(b); These statements would normally go in the constructor for the frame class. 18

19 Adding Components to a Frame ButtonTest is a modified version of FrameTest. ButtonTest defines a subclass of Frame named ButtonTestFrame, and then creates an instance of ButtonTestFrame. Actions taken by the ButtonTestFrame constructor: 1. Invokes the superclass constructor (the constructor for Frame), passing it the title of the frame. 2. Calls setlayout to specify how the components inside the frame will be laid out. 3. Creates a Button object. 4. Calls add to add the button to the frame. 19

20 ButtonTest.java // Displays a frame containing a single button. // WARNING: Frame cannot be closed. import java.awt.*; // Driver class public class ButtonTest { public static void main(string[] args) { Frame f = new ButtonTestFrame("Button Test"); f.setsize(150, 100); f.setvisible(true); } } // Frame class class ButtonTestFrame extends Frame { public ButtonTestFrame(String title) { super(title); setlayout(new FlowLayout()); Button b = new Button("Testing"); add(b); } } Do we save two classes in the same java file? 20

21 Adding Components to a Frame Frame created by the ButtonTest program: Pressing the Testing button has no effect. 21

22 Adding Components to a Frame Instead of calling setsize, the main method in ButtonTest could have called pack: f.pack(); pack makes the frame just large enough to display the components within it: Regardless of whether setsize or pack is called, the user can manually resize the frame. 22

23 Adding Components to a Frame It s not necessary to have two separate classes, (ButtonTest and ButtonTestFrame). By moving the main method from ButtonTest to ButtonTestFrame, the program could be condensed to one class (ButtonTestFrame). 23

24 Exercise Create a window that has three buttons. What are the main steps? 24

25 12.3 Event Listeners When the user performs an action, Java creates an object containing information about the event. Responding to an event is done by writing a method that can be called when the event occurs. Steps involved in handling an event: 1. The user performs an action, causing an event to be triggered (or fired). 2. An object is created that contains information about the event, including an indication of which component was involved. 3. A method that belongs to a listener object is called. The object created in step 2 is passed to the method. 25

26 Events When an event occurs, an object is created that contains information about the event. This object will belong to one of several different classes, depending on the nature of the event. These classes all belong to the java.awt.event package. Java divides events into two groups: high-level events and low-level events. 26

27 High-level events: Class Name Events Description of Event ActionEvent A significant action has been performed on a component (a button was pressed, a list item was double-clicked, or the Enter key was pressed in a text field). AdjustmentEvent The state of an adjustable component (such as a scrollbar) has changed. ItemEvent An item has been selected (or deselected) within a checkbox, choice menu, or list. TextEvent The contents of a text area or text field have changed. 27

28 Events Low-level events include moving the mouse or pressing a key. One low-level event is WindowEvent, which occurs when the status of a window has changed. In particular, a WindowEvent occurs when the user attempts to close a window. 28

29 Interfaces Event-handling requires the use of interfaces. An interface looks like a class, except that its methods aren t fully defined. Each method in an interface has a name, a parameter list, and a result type, but no body. One common interface is named ActionListener: public interface ActionListener extends EventListener { public void actionperformed(actionevent evt); } This resembles a class declaration, except that the word class has been replaced by interface, and the actionperformed method has no body. 29

30 Interfaces An interface is nothing but a pattern that will be used later to define real classes. A class implements an interface by agreeing to provide bodies for all methods in the interface. A class that implements the ActionListener interface would have to provide a method named actionperformed with one parameter of type ActionEvent and a result type of void. 30

31 Interfaces The keyword implements is used to tell the compiler that a class will implement a particular interface. A class that implements the ActionListener interface: class class-name implements ActionListener { public void actionperformed(actionevent evt) { } // Variables, constructors, and methods, // if desired } The class may contain any number of variables, constructors, and methods. 31

32 Creating Event Listeners To handle an event, it s necessary to create an event listener object. This object will be registered with a component; when an event occurs that involves the component, one of the listener s methods will be called. An event listener will be an instance of a listener class defined by the programmer. 32

33 Creating Event Listeners A listener class must implement one of the interfaces that belong to the java.awt.event package. Listener interfaces for high-level events: Interface Name ActionListener Required Method actionperformed(actionevent evt) AdjustmentListener adjustmentvaluechanged(adjustmentevent evt) ItemListener TextListener itemstatechanged(itemevent evt) textvaluechanged(textevent evt) Each interface contains a single method. The access modifier for each method is public, and the result type is void. 33

34 Creating Event Listeners There s a similar set of listener interfaces for lowlevel events. The listener interface for WindowEvent is named WindowListener. 34

35 Creating Event Listeners Pressing a button is an action event, so the listener class for a button would need to implement the ActionListener interface. To implement this interface, the class must define a public void method named actionperformed with a parameter of type ActionEvent. An example of a listener for an action event: class ButtonListener implements ActionListener { public void actionperformed(actionevent evt) { } } 35

36 Creating Event Listeners After writing a listener class, the next step is to create an instance of the class and connect it to a particular component. In the simplest case, a single listener object will be attached to a single component. Suppose that b is a Button object: Button b = new Button("Change Color"); A listener object can be created by using the constructor for the listener class: ButtonListener listener = new ButtonListener(); 36

37 Creating Event Listeners listener can now be registered as an action listener for the button: b.addactionlistener(listener); It s sometimes possible to save a statement by combining the creation of the listener object with the call of addactionlistener: b.addactionlistener(new ButtonListener()); 37

38 Creating Event Listeners Calling addactionlistener creates a link between the Button object and its listener: When the user presses the button, the ButtonListener object s actionperformed method will be called. 38

39 Creating Event Listeners Because ButtonListener implements the ActionListener interface, the compiler can verify that it has an actionperformed method. The ActionListener interface acts as a sort of contract that ButtonListener agrees to honor. It s an error to pass an object to addactionlistener unless the object belongs to a class that implements ActionListener. 39

40 Creating Event Listeners The ButtonTest program displays a Testing button, but pressing the button has no effect. Making the button work involves defining a listener class that implements the ActionListener interface, creating an instance of the class, and attaching it to the button. The ButtonTest2 program is similar to ButtonTest, but the window will close when the button is pressed. Changes are highlighted in bold. 40

41 ButtonTest2.java // Displays a frame containing a single "Close window" // button. The frame can be closed by pressing the button. import java.awt.*; import java.awt.event.*; // Driver class public class ButtonTest2 { public static void main(string[] args) { Frame f = new ButtonTestFrame("Button Test"); f.setsize(150, 100); f.setvisible(true); } } 41

42 // Frame class class ButtonTestFrame extends Frame { public ButtonTestFrame(String title) { super(title); setlayout(new FlowLayout()); Button b = new Button("Close window"); add(b); b.addactionlistener(new ButtonListener()); } } // Listener for button class ButtonListener implements ActionListener { public void actionperformed(actionevent evt) { System.exit(0); } } 42

43 Creating Event Listeners Frame created by the ButtonTest2 program: 43

44 Creating Event Listeners Pressing the Close window button causes a call of the actionperformed method for the button s listener object. This method calls System.exit, which causes the program to terminate and the frame to disappear. When a program terminates, any windows that it created are automatically closed. 44

45 Adapter Classes To make the Close button work, a WindowEvent listener is needed. A class that implements the WindowListener interface would have to contain several methods. There s an easier technique: use the WindowAdapter class from the java.awt.event package. This class implements the WindowListener interface, although the methods that it provides are all empty. 45

46 Adapter Classes The listener class will extend the WindowAdapter class and override the windowclosing method. It will then inherit all the other methods it needs. WindowAdapter is an example of an adapter class a class that can be extended instead of implementing an interface. Java provides matching adapter classes for most interfaces that have two or more methods. 46

47 Adapter Classes The ButtonTest3 program is a modification of ButtonTest2. The new WindowCloser class extends WindowAdapter and provides a windowclosing method of its own. The constructor for ButtonTestFrame now calls addwindowlistener to install a WindowCloser object as a listener for window events. 47

48 ButtonTest3.java // Displays a frame containing a single "Close window" // button. The frame can be closed by pressing either the // "Close window" button or the frame's "close" button. import java.awt.*; import java.awt.event.*; // Driver class public class ButtonTest3 { public static void main(string[] args) { Frame f = new ButtonTestFrame("Button Test"); f.setsize(150, 100); f.setvisible(true); } } 48

49 // Frame class class ButtonTestFrame extends Frame { public ButtonTestFrame(String title) { super(title); setlayout(new FlowLayout()); Button b = new Button("Close window"); add(b); b.addactionlistener(new ButtonListener()); } } // Attach window listener addwindowlistener(new WindowCloser()); // Listener for button class ButtonListener implements ActionListener { public void actionperformed(actionevent evt) { System.exit(0); } } 49

50 // Listener for window class WindowCloser extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } } 50

51 Adapter Classes When a window event occurs, one of the methods in the WindowCloser class will be called. If the event is caused by the user attempting to close the window, the windowclosing method is called, and the program terminates. Any other window event will cause one of WindowCloser s inherited methods to be called. These methods are empty, so nothing will happen. 51

52 12.4 Inner Classes The ChangeColor program will also have a single button. Pressing the button will change the background color of the frame. The background will initially be white: 52

53 The ChangeColor Program Pressing the button once will change the background to black: Pressing it again will cause the background to return to white. 53

54 The setbackground and getbackground Methods Changing the background color of a frame is done by calling the setbackground method, which is inherited from the Component class: setbackground(color.black); The getbackground method (also inherited from Component) returns the current background color. 54

55 Writing the ChangeColor Program The button listener in ChangeColor will change the frame s background color instead of causing the program to terminate: class ButtonListener implements ActionListener { public void actionperformed(actionevent evt) { if (getbackground() == Color.white) setbackground(color.black); else setbackground(color.white); } } 55

56 Writing the ChangeColor Program Unfortunately, the compiler won t allow the listener to call getbackground or setbackground, because those methods don t belong to the ButtonListener class or its superclass (Object). The actionperformed method needs to get (and set) the background for the frame, not the background for the ButtonListener object itself (which doesn t have a background, anyway). 56

57 Writing the ChangeColor Program Problems of this sort are common when writing a listener class because listeners often need access to variables or methods that belong to the frame. There s an easy way to solve such a problem: put the listener class inside the frame class. A class that s nested inside another class is said to be an inner class. Inner class methods have access to variables and methods in the enclosing class, allowing the inner class to serve as a helper for the enclosing class. 57

58 ChangeColor.java // Displays a frame containing a single button. Pressing the // button causes the background of the frame to change from // white to black or from black to white. import java.awt.*; import java.awt.event.*; // Driver class public class ChangeColor { public static void main(string[] args) { Frame f = new ChangeColorFrame("Change Color"); f.setsize(160, 100); f.setvisible(true); } } 58

59 // Frame class class ChangeColorFrame extends Frame { public ChangeColorFrame(String title) { // Set title, layout, and background color super(title); setlayout(new FlowLayout()); setbackground(color.white); // Add "Change color" button to frame and attach listener Button b = new Button("Change color"); add(b); b.addactionlistener(new ButtonListener()); } // Attach window listener addwindowlistener(new WindowCloser()); 59

60 // Listener for button class ButtonListener implements ActionListener { public void actionperformed(actionevent evt) { if (getbackground() == Color.white) setbackground(color.black); else setbackground(color.white); } } } // Listener for window class WindowCloser extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } } 60

61 12.5 Attaching Listeners to Multiple Components If a program has two buttons, one possibility is to attach the second button to the same ButtonListener object: The ButtonListener object s actionperformed method will be called when either button is pressed. 61

62 Using Multiple Listeners The other possibility is to create a different listener object for the second button: 62

63 Using Multiple Listeners The second listener could be an instance of a different listener class: 63

64 Determining the Source of an Event If two or more buttons are connected to a single listener, its actionperformed method will need to determine which button was pressed. Ways to solve this problem: Compare the source of the event (the component that triggered the method call) to see which Button object it matches. Test the event s action command to see which button label it matches. 64

65 The getsource Method If evt is an instance of any event class, the source of the event can be found by calling getsource: Object source = evt.getsource(); Because events can be caused by a variety of components, getsource returns an Object reference. To determine which component fired the event, the value returned by getsource can be compared with the variables containing the components: if (source == testbutton) 65

66 The getactioncommand Method The other way to determine the origin of a button press is to use the getactioncommand method. String label = evt.getactioncommand(); This method can be used only with action events, such as button presses. In the case of a button press, getactioncommand returns the label on the button. A statement that checks whether the button labeled "Testing" was pressed: if (label.equals("testing")) 66

67 Example: A Single Listener The ChangeColor2 program displays two buttons, labeled Lighter and Darker : 67

68 Example: A Single Listener Pressing the Lighter button will lighten the background slightly: 68

69 Example: A Single Listener Pressing Darker will darken it: Each button can be pressed more than once, causing the background to become successively lighter or darker. 69

70 Example: A Single Listener It s possible to use a single listener object for both buttons. Alternatively, there could be two listeners, one for each button. The ChangeColor2 program will use a single listener. The listener s actionperformed method will determine which button was pressed by testing the string returned by getactioncommand. There are only two buttons, so the string will be either "Lighter" or "Darker". 70

71 ChangeColor2.java // Displays a frame containing two buttons. Pressing the // "Lighter" button lightens the background of the frame. // Pressing the "Darker" button darkens the background. import java.awt.*; import java.awt.event.*; // Driver class public class ChangeColor2 { public static void main(string[] args) { Frame f = new ChangeColorFrame("Change Color"); f.setsize(160, 100); f.setvisible(true); } } 71

72 // Frame class class ChangeColorFrame extends Frame { public ChangeColorFrame(String title) { // Set title, layout, and background color super(title); setlayout(new FlowLayout()); setbackground(color.gray); } // Create button listener ButtonListener listener = new ButtonListener(); // Add "Lighter" button to frame and attach listener Button b = new Button("Lighter"); add(b); b.addactionlistener(listener); // Add "Darker" button to frame and attach listener b = new Button("Darker"); add(b); b.addactionlistener(listener); // Attach window listener addwindowlistener(new WindowCloser()); 72

73 // Listener for both buttons class ButtonListener implements ActionListener { public void actionperformed(actionevent evt) { Color currentbackground = getbackground(); String buttonlabel = evt.getactioncommand(); } } // Test label on button and change background color if (buttonlabel.equals("lighter")) setbackground(currentbackground.brighter()); else setbackground(currentbackground.darker()); } // Listener for window class WindowCloser extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } } 73

74 Example: A Single Listener The brighter and darker methods belong to the Color class. brighter returns a brighter version of the Color object that called it; darker returns a darker version. 74

75 Example: Separate Listeners The ChangeColor3 program is similar to ChangeColor2, except that it uses separate listeners for the Lighter and Darker buttons. Using separate listeners requires an additional listener class. On the other hand, the actionperformed method in each class will be very short, because there s no need to test which button was pressed. 75

76 ChangeColor3.java // Displays a frame containing two buttons. Pressing the // "Lighter" button lightens the background of the frame. // Pressing the "Darker" button darkens the background. import java.awt.*; import java.awt.event.*; // Driver class public class ChangeColor3 { public static void main(string[] args) { Frame f = new ChangeColorFrame("Change Color"); f.setsize(160, 100); f.setvisible(true); } } 76

77 // Frame class class ChangeColorFrame extends Frame { public ChangeColorFrame(String title) { // Set title, layout, and background color super(title); setlayout(new FlowLayout()); setbackground(color.gray); // Add "Lighter" button to frame and attach listener Button b = new Button("Lighter"); add(b); b.addactionlistener(new LighterButtonListener()); // Add "Darker" button to frame and attach listener b = new Button("Darker"); add(b); b.addactionlistener(new DarkerButtonListener()); } // Attach window listener addwindowlistener(new WindowCloser()); 77

78 // Listener for "Lighter" button class LighterButtonListener implements ActionListener { public void actionperformed(actionevent evt) { setbackground(getbackground().brighter()); } } // Listener for "Darker" button class DarkerButtonListener implements ActionListener { public void actionperformed(actionevent evt) { setbackground(getbackground().darker()); } } } // Listener for window class WindowCloser extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } } 78

79 Exercise Create a window with three buttons as described below: Button 1: the number button. Click this button generate a random number between 0 and 1 and shows the number on the button. Button 2: the number button. Click this button generate a random number between 0 and 1 and shows the number on the button. Button 3: the add button. Click this button will add the numbers of button 1 and button 2 and print the result. 79

80 12.6 Layout The layout of components within a container remains a mystery. Consider the ChangeColor2 frame: Why are the buttons placed side by side? Why are the buttons centered within the frame? 80

81 Layout Managers These decisions are made by an object known as a layout manager. Every container has a default layout manager that determines the sizes and positions of components within the container. This layout manager can be replaced if desired. One reason that Java uses layout managers is so that containers can be resized gracefully. Each time a container is resized, the container s layout manager determines new sizes and positions for the components in the container. 81

82 Layout Manager Classes The java.awt package provides five layout manager classes: Class Name BorderLayout CardLayout FlowLayout 82 Behavior Arranges components along the sides of the container and in the middle. Arrange components in cards. Only one card is visible at a time. Arranges components in variable-length rows. GridBagLayout Aligns components horizontally and vertically; components can be of different sizes. GridLayout Arranges components in fixed-length rows and columns.

83 Layout Manager Classes FlowLayout and GridLayout are the easiest layout managers to understand. BorderLayout and CardLayout are somewhat harder to use. GridBagLayout is the most powerful layout manager, but it s also the most complicated. 83

84 Layout Manager Classes Choosing a layout manager is done by calling the setlayout method. (setlayout belongs to the Container class, so it s inherited by all container classes.) To select FlowLayout as the layout manager for a frame, put the following call of setlayout in the frame s constructor: setlayout(new FlowLayout()); If no layout manager is specified for a frame, the default is BorderLayout. 84

85 The FlowLayout Class The FlowLayout layout manager can handle any number of components. The components are laid out side by side from left to right. When no more components will fit in a row, FlowLayout starts a new row. 85

86 The FlowLayout Class Suppose that a frame containing seven buttons uses FlowLayout as its layout manager. The number of buttons that can be squeezed into a row depends on how wide the frame is: 86

87 The FlowLayout Class The simplest way to use FlowLayout is to call its no-arg constructor and pass the resulting object to setlayout: setlayout(new FlowLayout()); By default, components will be separated by five pixels of space and centered in each row. 87

88 The FlowLayout Class The alignment can be specified explicitly by passing FlowLayout.LEFT, FlowLayout.RIGHT, or FlowLayout.CENTER to the constructor: setlayout(new FlowLayout(FlowLayout.LEFT)); The horizontal and vertical gaps between components can also be passed to the constructor: setlayout(new FlowLayout(FlowLayout.LEFT, 20, 10)); 88

89 The GridLayout Class The GridLayout layout manager places components in rows, with each row (except possibly the last) having an equal number of components: 89

90 The GridLayout Class If a frame with a GridLayout is resized, the components within the frame change size as well: 90

91 The GridLayout Class The GridLayout constructor requires that the number of rows and columns be specified: setlayout(new GridLayout(4, 5)); Components will be arranged in four rows and five columns, with no space between components. If space is desired between components, two more arguments the horizontal gap and the vertical gap are supplied to the constructor: setlayout(new GridLayout(4, 5, 20, 10)); 91

92 The GridLayout Class GridLayout works best when all components in the container are the same kind (all buttons, for example), because it forces the components to be the same size. If the container contains a mixture of components, some components may end up appearing too large while others look too small. 92

93 The BorderLayout Class The BorderLayout layout manager can handle up to five components. Four of the components can be positioned against the sides of the container, with the fifth occupying the center of the container. 93

94 The BorderLayout Class The positions in a BorderLayout are named North, South, East, West, and Center: 94

95 The BorderLayout Class The North and South components are stretched to the width of the container. The West and East components are stretched vertically to fill the gap between North and South. The Center component expands in both directions to fill any remaining space. 95

96 The BorderLayout Class The no-arg version of the BorderLayout constructor leaves no space between components: setlayout(new BorderLayout()); A different constructor is used if space is needed between components: setlayout(new BorderLayout(20, 10)); 96

97 The BorderLayout Class When a container uses BorderLayout as its layout manager, a different version of the add method is required: add("center", new Button("Test")); The first argument must be either "North", "South", "East", "West", or "Center". 97

98 The BorderLayout Class If a frame with a BorderLayout is resized, the heights of the North and South components don t change: The widths of the East and West components also remain the same. 98

99 The BorderLayout Class BorderLayout doesn t require that all five positions be used; unused positions are filled by neighboring components. This property makes BorderLayout a surprisingly versatile layout tool. 99

100 Preferred Sizes Every component has a preferred size. For example, the preferred size of a button is determined by the size of the label on the button the longer the label, the wider the button. 100

101 Preferred Sizes Each layout manager has a different way of dealing with preferred sizes: FlowLayout: Honors the preferred sizes of all components. GridLayout: Ignores the preferred sizes of all components. BorderLayout: Honors the preferred widths of the East and West components. Honors the preferred heights of the North and South components. Ignores the preferred size of the Center component. 101

102 Preferred Sizes The layout examples shown earlier illustrate this behavior: The buttons in the FlowLayout example stayed the same size (their preferred size), no matter what the size of the frame was. The buttons in the GridLayout example expanded to fill the entire frame. In the BorderLayout example, the North and South buttons kept their preferred height, while the East and West buttons kept their preferred width. 102

103 Panels A panel an instance of the Panel class is another kind of container. A panel is rectangular but has no border. When a panel is placed inside another container, it blends in seamlessly. Each panel has its own layout manager. A panel can be used to create a group of components that is treated as a single component. 103

104 Panels Panel objects can be created by using the no-arg version of the Panel constructor: Panel p = new Panel(); By default, the layout manager for a panel is FlowLayout. A different layout manager can be chosen by calling setlayout: p.setlayout(new BorderLayout()); Passing the layout manager to the Panel constructor avoids a separate call of setlayout: Panel p = new Panel(new BorderLayout()); 104

105 Panels Once a panel has been created, components are added to it by calling the add method: p.add("center", new Button("Test")); The panel itself will need to be added to a frame or other container. 105

106 Panels Consider the problem of creating a frame with the following appearance: 106

107 Panels The top 12 buttons will need to be grouped into a single component using a panel. The panel will use a GridLayout to force the buttons into four rows and three columns. To make sure that this panel is positioned above the Dial button, the frame itself will need to use a BorderLayout. If the Dial button is placed at the South position and the panel at the Center position, the panel will expand to fill the frame. 107

108 Panels To keep the Dial button at the correct size, it will need to be put in a panel of its own, which is then placed at the South position. This panel will have a FlowLayout manager, which will center the button and keep it at its preferred size. The panel containing the 12 buttons will also need to be put inside another panel, to keep the buttons from growing if the frame is resized. 108

109 Panels Summary of panels needed: buttonpanel: Contains 12 buttons; uses GridLayout. centerpanel: Contains buttonpanel; uses FlowLayout. bottompanel: Contains Dial button; uses FlowLayout. 109

110 Panels A figure showing the panels as dashed rectangles: 110

111 Panels Statements to create the phone layout: Panel buttonpanel = new Panel(); buttonpanel.setlayout(new GridLayout(4, 3, 10, 10)); for (int i = 1; i <= 9; i++) buttonpanel.add(new Button(i + "")); buttonpanel.add(new Button("*")); buttonpanel.add(new Button("0")); buttonpanel.add(new Button("#")); Panel centerpanel = new Panel(); centerpanel.add(buttonpanel); add("center", centerpanel); Panel bottompanel = new Panel(); bottompanel.add(new Button("Dial")); add("south", bottompanel); 111

112 12.7 Creating and Using Components For each component, it s important to know three things: How to create the component What kind of event(s) it fires How to determine the current state of the component 112

113 Checkboxes A checkbox is a small box that the user can check by clicking with the mouse: Clicking on the box causes a check mark to appear: Clicking a second time removes the check mark from the box. 113

114 Checkboxes A checkbox normally has a label, which is passed to the Checkbox constructor as an argument: Checkbox cb = new Checkbox("Enable sounds"); The no-arg version of the Checkbox constructor creates a checkbox without a label: Checkbox cb = new Checkbox(); By default, a new checkbox is in the off state (no check mark). Creating a checkbox that s on requires using a constructor that takes the state as its second argument: Checkbox cb = new Checkbox("Enable sounds", true); 114

115 Checkboxes When a checkbox is clicked, an item event occurs. Detecting this event requires writing a listener class that implements the ItemListener interface. Implementing this interface requires writing a method named itemstatechanged: class CheckboxListener implements ItemListener { public void itemstatechanged(itemevent evt) { } } The additemlistener method can be used to attach a listener to the checkbox: cb.additemlistener(new CheckboxListener()); 115

116 Checkboxes Not every checkbox will require a listener. A program may wait for some other event to occur and then examine the checkboxes to see which ones are currently checked. The getstate method returns the state of a checkbox: boolean state = cb.getstate(); The setstate method changes the state of a checkbox: cb.setstate(true); 116

117 Checkbox Groups A checkbox group is a collection of checkboxes in which only one box can be checked at a time: Checkboxes that are related in this way are often referred to as radio buttons. Checkboxes that belong to a group often have a different appearance than individual checkboxes. Under Windows, boxes in a group are round instead of square. 117

118 Checkbox Groups The first step in creating a group of checkboxes is to create a CheckboxGroup object: CheckboxGroup musicgroup = new CheckboxGroup(); The next step is to create the checkboxes, supplying the CheckboxGroup object as the second argument to the Checkbox constructor: Checkbox rockbox = new Checkbox("Rock", musicgroup, true); Checkbox jazzbox = new Checkbox("Jazz", musicgroup, false); Checkbox classicalbox = new Checkbox("Classical", musicgroup, false); 118

119 Choice Menus A choice menu (or popup menu) displays one of several items: When the user presses on the arrow button with the mouse, the full list of choices pops up: 119

120 Choice Menus Creating a choice menu requires two steps. The first step is to create a Choice object: Choice countrychoice = new Choice(); The second step is to add menu items using the add method: countrychoice.add("u.s.a."); countrychoice.add("canada"); countrychoice.add("mexico"); The order in which the items are added determines the order in which they ll appear on the menu. 120

121 Choice Menus When the user pops up the menu and makes a choice, an item event occurs. As a result, the listener class for a choice menu will need to implement the ItemListener interface. The getselecteditem method returns the selected item: String itemselected = countrychoice.getselecteditem(); The getselectedindex method returns the position of the selected item: int itemindex = countrychoice.getselectedindex(); The first item in the list has index

122 Labels A label is a rectangular area containing a text string: A label has no border around it; the user sees nothing but the text. Labels are often placed next to other components to indicate their meaning or function. The user can t change a label s text; there are no events defined for labels. 122

123 Labels One of the Label constructors takes a single argument, the text to be displayed within the label: Label lastname = new Label("Enter last name:"); By default, the text is left-justified within the label. The desired alignment can be passed as a second argument to the Label constructor: Label lastname = new Label("Enter last name:", Label.CENTER); Possible values are Label.CENTER, Label.LEFT, and Label.RIGHT. 123

124 Labels The gettext method returns the text of a label: String labelcontents = lastname.gettext(); The settext method changes the text of a label: lastname.settext("enter first name:"); 124

125 Lists A list is a rectangle containing a series of items: The user can choose an item by clicking on it: 125

126 Lists If not all list items are visible, a scrollbar appears to the right of the list: 126

127 Lists Creating a list is similar to creating a choice menu. The first step is to create a List object: List countrylist = new List(); By default, four items will be visible at a time. The number of visible items can be specified if desired: List countrylist = new List(5); Once the list has been created, the add method is used to add items to it: countrylist.add("u.s.a."); countrylist.add("canada"); countrylist.add("mexico"); 127

128 Lists Single-clicking on a list item causes an item event. Double-clicking causes an action event. To determine which item was selected, either getselectedindex or getselecteditem can be called. 128

129 Scrollbars A scrollbar is a sliding bar. Scrollbars can be either horizontal: or vertical: 129

130 Scrollbars Each scrollbar represents a number chosen from a range of integers, such as 0 to 100 or 32 to 212. The width of the sliding portion of the scrollbar (the scroll box or bubble ) must be at least 1 (measured in the scrollbar s own units, not in pixels), but it can be wider if desired. 130

131 Scrollbars The largest value that the user can select is the maximum value of the scrollbar s range minus the width of the scroll box. If the scrollbar has a range of 0 to 100, and the scroll box has a width of 10, then the largest value that the user can select is =

132 Scrollbars Ways for the user to change the value of a scrollbar: Drag the scroll box to a different position. Click on the arrow buttons, which changes the value by a small amount, known as the unit increment. (By default, the unit increment is 1.) Click in the area between an arrow button and the scroll box, which changes the value by a larger amount, known as the block increment. (By default, the block increment is 10.) 132

133 Scrollbars One Scrollbar constructor has five arguments: Scrollbar sb = new Scrollbar(Scrollbar.HORIZONTAL, 50, 1, 0, 100); The first argument (Scrollbar.HORIZONTAL or Scrollbar.VERTICAL) specifies the scrollbar s orientation. The fourth and fifth arguments specify the minimum and maximum values of the scrollbar s range. The second argument is the initial value of the scrollbar. The third argument is the width of the scroll box, which must be at least

134 Scrollbars When the user adjusts a scrollbar, an adjustment event occurs. Handling the event requires writing a class that implements the AdjustmentListener interface. This class must contain a method named adjustmentvaluechanged: class ScrollbarListener implements AdjustmentListener { public void adjustmentvaluechanged(adjustmentevent evt) { } } 134

135 Scrollbars The addadjustmentlistener method is used to attach a listener to the scrollbar: sb.addadjustmentlistener(new ScrollbarListener()); The getvalue method returns the current value of a scrollbar: int value = sb.getvalue(); The setvalue method changes the value of a scrollbar: sb.setvalue(newvalue); 135

136 Text Areas A text area is capable of displaying multiple lines of text: Scrollbars at the bottom and right side make it possible for the user to view text that s not otherwise visible. 136

137 Text Areas There are four ways to create a TextArea object, depending on: Whether or not text is to be displayed initially. Whether the number of rows and columns is specified. 137

138 Text Areas Assume that quote is the following string: String quote = "To be, or not to be: that is the question:\n" + "Whether 'tis nobler in the mind to suffer\n" + "The slings and arrows of outrageous fortune,\n" + "Or to take arms against a sea of troubles,\n" + "And by opposing end them? To die: to sleep;\n" + "No more; and, by a sleep to say we end\n" + "The heartache and the thousand natural shocks\n" + "That flesh is heir to, 'tis a consummation\n" + "Devoutly to be wish'd. To die, to sleep;\n" + "To sleep: perchance to dream: ay, there's the rub;\n" + "For in that sleep of death what dreams may come"; Notice that new-line characters are used to separate lines. 138

139 Text Areas The no-arg constructor creates an empty text area with a default size: TextArea ta = new TextArea(); To create a nonempty text area, a string containing the desired text is passed as an argument: TextArea ta = new TextArea(quote); The number of rows and columns can be specified: TextArea ta = new TextArea(10, 20); It s also possible to specify values for both the text and the rows and columns: TextArea ta = new TextArea(quote, 10, 20); 139

140 Text Areas A text area can be made editable or not editable by calling seteditable and passing either true or false: ta.seteditable(false); // Not editable Text areas are editable by default. A text event occurs whenever the user changes any of the text in a text area. 140

141 Text Areas Detecting a text event requires writing a class that implements the TextListener interface. Implementing this interface involves writing a method named textvaluechanged: class TextAreaListener implements TextListener { public void textvaluechanged(textevent evt) { } } The addtextlistener method attaches a listener to a text area: ta.addtextlistener(new TextAreaListener()); 141

142 Text Areas The gettext method returns the current contents of a text area: String text = ta.gettext(); gettext returns a single string, with new-line characters marking breaks between lines. The settext method replaces the contents of a text area: ta.settext("line 1\nLine 2\nLine 3"); The append method adds text to the end of a text area: ta.append("\nline 4"); 142

143 Text Fields A text field contains a single line of text: The TextField class has four constructors, whose arguments specify the contents of the text field and/or the number of columns in the text field: TextField tf = new TextField(); TextField tf = new TextField("Your name here"); TextField tf = new TextField(40); TextField tf = new TextField("Your name here", 40); 143

144 Text Fields Text fields are editable by default. A text field can be made not editable by calling seteditable with false as the argument: tf.seteditable(false); // Not editable A text field can fire text events, which occur when the user modifies the contents of the text field. An action event occurs when the user presses the Enter key after entering data into a text field. Both text events and action events are possible only if the text field is editable. 144

145 Text Fields The methods for text fields, which include gettext and settext, are similar to those for text areas. This similarity isn t surprising, because the TextArea and TextField classes inherit much of their behavior from their superclass, TextComponent. Text fields don t support the append method, however. 145

146 12.8 Examples The ConvertTemp, ShowDefinition, and PickColor programs illustrate the use of various GUI components. 146

147 Using Labels and Text Fields: Temperature Conversion ConvertTemp is a GUI version of the Chapter 2 program that converts Fahrenheit temperatures to Celsius. The new version will also be able to convert temperatures from Celsius to Fahrenheit. ConvertTemp will display the following frame: 147

148 Using Labels and Text Fields: Temperature Conversion If the user enters a value in the Fahrenheit field and presses the Enter key, the corresponding Celsius temperature will appear in the Celsius field: 148

149 Using Labels and Text Fields: Temperature Conversion Likewise, if the user enters a value in the Celsius field and presses the Enter key, the corresponding Fahrenheit temperature will appear in the Fahrenheit field: Temperatures displayed by the program will be rounded to two decimal places. 149

150 Using Labels and Text Fields: Temperature Conversion Designing this program requires confronting two issues: layout and event-handling. The GUI components will be two labels and two text fields. The layout manager can be GridLayout with two rows and two columns. GridLayout will make the labels and text fields all the same size. The text fields will need to be declared as instance variables so that a listener will be able to modify one of the text fields when the other is changed. 150

151 Using Labels and Text Fields: Temperature Conversion ConvertTemp will need at least two listeners. One listener will cause the program to terminate when the user closes the frame. Another listener will be called when the user enters data into either one of the text fields. Although one listener is enough for this purpose, the program is easier to understand if two listeners are used, one for each field. 151

152 Using Labels and Text Fields: Temperature Conversion The listener classes, FahrenheitListener and CelsiusListener, will each have an actionperformed method. Actions taken by this method: Retrieve the user s input from one of the text fields and convert it to double form. Convert this number from one temperature scale to the other. Round the result to two decimal places and display it in the other text field. Convert.toDouble (from the jpb package) is used to convert the user s input into a double value. 152

153 ConvertTemp.java // Converts a Fahrenheit temperature entered by the user to // Celsius, or vice versa import java.awt.*; import java.awt.event.*; import jpb.*; // Driver class public class ConvertTemp { public static void main(string[] args) { Frame frame = new ConvertTempFrame("Temperature Conversion"); frame.setsize(150, 75); frame.setvisible(true); } } 153

154 // Frame class class ConvertTempFrame extends Frame { private TextField fahrenfield = new TextField(); private TextField celsiusfield = new TextField(); // Constructor public ConvertTempFrame(String title) { // Set title for frame and choose layout super(title); setlayout(new GridLayout(2, 2)); // Add Fahrenheit label and text field to frame; attach // listener to text field add(new Label("Fahrenheit")); add(fahrenfield); fahrenfield.addactionlistener(new FahrenheitListener()); 154

155 // Add Celsius label and text field to frame; attach // listener to text field add(new Label("Celsius")); add(celsiusfield); celsiusfield.addactionlistener(new CelsiusListener()); } // Attach window listener addwindowlistener(new WindowCloser()); // Listener for fahrenfield class FahrenheitListener implements ActionListener { public void actionperformed(actionevent evt) { String fahrenheitstring = fahrenfield.gettext(); double fahrenheit = Convert.toDouble(fahrenheitString); double celsius = (fahrenheit ) * 5.0 / 9.0; celsius = Math.rint(celsius * 100.0) / 100.0; celsiusfield.settext(celsius + ""); } } 155

156 // Listener for celsiusfield class CelsiusListener implements ActionListener { public void actionperformed(actionevent evt) { String celsiusstring = celsiusfield.gettext(); double celsius = Convert.toDouble(celsiusString); double fahrenheit = celsius * 9.0 / ; fahrenheit = Math.rint(fahrenheit * 100.0) / 100.0; fahrenfield.settext(fahrenheit + ""); } } } // Listener for window class WindowCloser extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } } 156

157 Using Lists and Text Areas: Showing Definitions The ShowDefinition program illustrates the use of lists and text areas. ShowDefinition will display a list of terms: 157

158 Using Lists and Text Areas: Showing Definitions When the user clicks on a term, the program will display the definition of the term in the text area: 158

159 Using Lists and Text Areas: Showing Definitions To make the text area as large as possible, ShowDefinition will use a BorderLayout, with the list of terms at West and the text area at Center. Single-clicking on a list item causes an item event, so the program will need a listener class that implements the ItemListener interface. The text area won t need a listener. 159

160 Using Lists and Text Areas: Showing Definitions The terms and definitions will be stored in parallel arrays named terms and definitions. When the user clicks on a list item, the getselectedindex method can be used to get the position of the selected term. The program will then display the definition at the same position in the definitions array. 160

161 ShowDefinition.java // Shows the definition of a term import java.awt.*; import java.awt.event.*; // Driver class public class ShowDefinition { public static void main(string[] args) { Frame f = new ShowDefinitionFrame("Show Definition"); f.setsize(300, 160); f.setvisible(true); } } 161

162 // Frame class class ShowDefinitionFrame extends Frame { private List termlist = new List(); private TextArea definitionarea = new TextArea(); private String[] terms = {"Button", "Checkbox", "Choice", "Label", "List", "Scrollbar", "TextArea", "TextField"}; private String[] definitions = {"A labeled button that can\nbe pressed", "A box that can be clicked\n\"on\" or \"off\"", "A menu that displays one\nitem at a time", "A string that can be\npositioned next to " + "other\ncomponents", "A scrolling list of items", "A sliding bar that can be\neither horizontal or " + "vertical", "A multiline area in which\ntext can be displayed " + "or\nedited", "A single line of text that\ncan be displayed " + "or\nedited"}; 162

163 // Constructor public ShowDefinitionFrame(String title) { // Set title for frame super(title); // Put terms in term list; add term list to frame for (int i = 0; i < terms.length; i++) termlist.add(terms[i]); termlist.additemlistener(new ListListener()); add("west", termlist); // Make definition area not editable and add to frame definitionarea.seteditable(false); add("center", definitionarea); } // Attach window listener addwindowlistener(new WindowCloser()); 163

164 // Listener for termlist class ListListener implements ItemListener { public void itemstatechanged(itemevent evt) { int index = termlist.getselectedindex(); definitionarea.settext(definitions[index]); } } } // Listener for window class WindowCloser extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } } 164

165 Using Labels and Scrollbars: Picking Colors The PickColor program illustrates the use of labels and scrollbars. The program will display a frame containing three scrollbars, representing the colors red, green, and blue, and three labels. 165

166 Using Labels and Scrollbars: Picking Colors Initially, each scrollbar will be in its middle position, representing the color gray: 166

167 Using Labels and Scrollbars: Picking Colors By moving the scrollbars, the user can experiment with different color combinations: 167

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

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

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

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

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

CHAPTER 2. Java Overview

CHAPTER 2. Java Overview Networks and Internet Programming (0907522) CHAPTER 2 Java Overview Instructor: Dr. Khalid A. Darabkh Objectives The objectives of this chapter are: To discuss the classes present in the java.awt package

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

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

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

The Java Programming Language Basics. Identifiers, Keywords, and Types. Expressions and Flow Control. Object-Oriented Programming. Objects and Classes

The Java Programming Language Basics. Identifiers, Keywords, and Types. Expressions and Flow Control. Object-Oriented Programming. Objects and Classes Building GUIs 8 Course Map This module covers setup and layout of graphical user interfaces. It introduces the Abstract Windowing Toolkit, a package of classes from which GUIs are built. Getting Started

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

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

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver Building a GUI in Java with Swing CITS1001 extension notes Rachel Cardell-Oliver Lecture Outline 1. Swing components 2. Building a GUI 3. Animating the GUI 2 Swing A collection of classes of GUI components

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

OBJECT ORIENTED PROGRAMMING. Java GUI part 1 Loredana STANCIU Room B616

OBJECT ORIENTED PROGRAMMING. Java GUI part 1 Loredana STANCIU Room B616 OBJECT ORIENTED PROGRAMMING Java GUI part 1 Loredana STANCIU loredana.stanciu@upt.ro Room B616 What is a user interface That part of a program that interacts with the user of the program: simple command-line

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

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

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

Programming Language Concepts: Lecture 8

Programming Language Concepts: Lecture 8 Programming Language Concepts: Lecture 8 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2009 PLC 2009, Lecture 8, 11 February 2009 GUIs and event

More information

Java Event Handling -- 1

Java Event Handling -- 1 Java Event Handling -- 1 Event Handling Happens every time a user interacts with a user interface. For example, when a user pushes a button, or types a character. 2 A Typical Situation: Scrollbar AWTEvent

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

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

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

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

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

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

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

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 - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1,

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1, Java - Applets C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1, 5.3.2. Java is not confined to a DOS environment. It can run with buttons and boxes in a Windows

More information

Java - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything.

Java - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything. Java - Applications C&G Criteria: 5.3.2, 5.5.2, 5.5.3 Java applets require a web browser to run independently of the Java IDE. The Dos based console applications will run outside the IDE but have no access

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

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.)

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.) Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String tostring() () void move(int dx,int dy) (int,int) void paint(graphicsg) (Graphics)

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

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

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

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

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

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

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

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

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

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

7. Program Frameworks

7. Program Frameworks 7. Program Frameworks Overview: 7.1 Introduction to program frameworks 7.2 Program frameworks for User Interfaces: - Architectural properties of GUIs - Abstract Window Toolkit of Java Many software systems

More information

Swing from A to Z Using Focus in Swing, Part 2. Preface

Swing from A to Z Using Focus in Swing, Part 2. Preface Swing from A to Z Using Focus in Swing, Part 2 By Richard G. Baldwin Java Programming, Lecture Notes # 1042 November 27, 2000 Preface Introduction Sample Program Interesting Code Fragments Summary What's

More information

Chapter 7: A First Look at GUI Applications

Chapter 7: A First Look at GUI Applications Chapter 7: A First Look at GUI Applications Starting Out with Java: From Control Structures through Objects Fourth Edition by Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley. All

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

Java AWT Windows, Text, & Graphics

Java AWT Windows, Text, & Graphics 2 AWT Java AWT Windows, Text, & Graphics The Abstract Windows Toolkit (AWT) contains numerous classes and methods that allow you to create and manage applet windows and standard windows that run in a GUI

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

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1 Block I Unit 2 Basic Constructs in Java M301 Block I, unit 2 1 Developing a Simple Java Program Objectives: Create a simple object using a constructor. Create and display a window frame. Paint a message

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

Java - Applets. public class Buttons extends Applet implements ActionListener

Java - Applets. public class Buttons extends Applet implements ActionListener Java - Applets Java code here will not use swing but will support the 1.1 event model. Legacy code from the 1.0 event model will not be used. This code sets up a button to be pushed: import java.applet.*;

More information

AWT DIALOG CLASS. Dialog control represents a top-level window with a title and a border used to take some form of input from the user.

AWT DIALOG CLASS. Dialog control represents a top-level window with a title and a border used to take some form of input from the user. http://www.tutorialspoint.com/awt/awt_dialog.htm AWT DIALOG CLASS Copyright tutorialspoint.com Introduction Dialog control represents a top-level window with a title and a border used to take some form

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

Graphical Interfaces

Graphical Interfaces Weeks 11&12 Graphical Interfaces All the programs that you have created until now used a simple command line interface, which is not user friendly, so a Graphical User Interface (GUI) should be used. The

More information

Graphical Applications

Graphical Applications Graphical Applications The example programs we've explored thus far have been text-based They are called command-line applications, which interact with the user using simple text prompts Let's examine

More information

Graphical Interfaces

Graphical Interfaces Weeks 9&11 Graphical Interfaces All the programs that you have created until now used a simple command line interface, which is not user friendly, so a Graphical User Interface (GUI) should be used. The

More information

An Introduction To Graphical User Interfaces

An Introduction To Graphical User Interfaces An Introduction To Graphical User Interfaces The event-driven model Building simple graphical interfaces in Java Components They are all types of graphical controls and displays available: Button, Canvas,

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

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

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

Graphical User Interfaces in Java - SWING

Graphical User Interfaces in Java - SWING Graphical User Interfaces in Java - SWING Graphical User Interfaces (GUI) Each graphical component that the user can see on the screen corresponds to an object of a class Component: Window Button Menu...

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

Java Applets / Flash

Java Applets / Flash Java Applets / Flash Java Applet vs. Flash political problems with Microsoft highly portable more difficult development not a problem less so excellent visual development tool Applet / Flash good for:

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

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { } CBOP3203 What Is an Event? Events Objects that describe what happened Event Sources The generator of an event Event Handlers A method that receives an event object, deciphers it, and processes the user

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

กล ม API ท ใช. Programming Graphical User Interface (GUI) Containers and Components 22/05/60

กล ม API ท ใช. Programming Graphical User Interface (GUI) Containers and Components 22/05/60 กล ม API ท ใช Programming Graphical User Interface (GUI) AWT (Abstract Windowing Toolkit) และ Swing. AWT ม ต งต งแต JDK 1.0. ส วนมากจะเล กใช และแทนท โดยr Swing components. Swing API ปร บปร งความสามารถเพ

More information

Chapter 12 Advanced GUIs and Graphics

Chapter 12 Advanced GUIs and Graphics Chapter 12 Advanced GUIs and Graphics Chapter Objectives Learn about applets Explore the class Graphics Learn about the classfont Explore the classcolor Java Programming: From Problem Analysis to Program

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

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

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Module 5 The Applet Class, Swings OOC 4 th Sem, B Div 2016-17 Prof. Mouna M. Naravani The layout manager helps lay out the components held by this container. When you set a layout to null, you tell the

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

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

Introduction This assignment will ask that you write a simple graphical user interface (GUI). Computing and Information Systems/Creative Computing University of London International Programmes 2910220: Graphical Object-Oriented and Internet programming in Java Coursework one 2011-12 Introduction

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

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

The AWT Package, Placing Components in Containers, CardLayout. Preface. Introduction

The AWT Package, Placing Components in Containers, CardLayout. Preface. Introduction Richard G Baldwin (512) 223-4758, baldwin@austin.cc.tx.us, http://www2.austin.cc.tx.us/baldwin/ The AWT Package, Placing Components in Containers, CardLayout Java Programming, Lecture Notes # 120, Revised

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

Building Graphical User Interfaces. GUI Principles

Building Graphical User Interfaces. GUI Principles Building Graphical User Interfaces 4.1 GUI Principles Components: GUI building blocks Buttons, menus, sliders, etc. Layout: arranging components to form a usable GUI Using layout managers. Events: reacting

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

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

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13 CONTENTS Chapter 1 Getting Started with Java SE 6 1 Introduction of Java SE 6... 3 Desktop Improvements... 3 Core Improvements... 4 Getting and Installing Java... 5 A Simple Java Program... 10 Compiling

More information

Building Graphical User Interfaces. Overview

Building Graphical User Interfaces. Overview Building Graphical User Interfaces 4.1 Overview Constructing GUIs Interface components GUI layout Event handling 2 1 GUI Principles Components: GUI building blocks. Buttons, menus, sliders, etc. Layout:

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

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

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

To gain experience using GUI components and listeners.

To gain experience using GUI components and listeners. Lab 5 Handout 7 CSCI 134: Fall, 2017 TextPlay Objective To gain experience using GUI components and listeners. Note 1: You may work with a partner on this lab. If you do, turn in only one lab with both

More information

JAVA NOTES GRAPHICAL USER INTERFACES

JAVA NOTES GRAPHICAL USER INTERFACES 1 JAVA NOTES GRAPHICAL USER INTERFACES Terry Marris 24 June 2001 5 TEXT AREAS 5.1 LEARNING OUTCOMES By the end of this lesson the student should be able to understand how to get multi-line input from the

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

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

Midterm assessment - MAKEUP Fall 2010

Midterm assessment - MAKEUP Fall 2010 M257 MTA Faculty of Computer Studies Information Technology and Computing Date: /1/2011 Duration: 60 minutes 1-Version 1 M 257: Putting Java to Work Midterm assessment - MAKEUP Fall 2010 Student Name:

More information

Swing/GUI Cheat Sheet

Swing/GUI Cheat Sheet General reminders To display a Swing component, you must: Swing/GUI Cheat Sheet Construct and initialize the component. Example: button = new JButton ("ButtonLabel"); Add it to the content pane of the

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 March 2, 2017 1. To introduce the notion of a component and some basic Swing components (JLabel, JTextField,

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

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling Overview Building Graphical User Interfaces Constructing GUIs Interface components GUI layout Event handling 4.1 GUI Principles AWT and Swing Components: GUI building blocks. Buttons, menus, sliders, etc.

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

Today. cisc3120-fall2012-parsons-lectiii.3 2

Today. cisc3120-fall2012-parsons-lectiii.3 2 MORE GUI COMPONENTS Today Last time we looked at some of the components that the: AWT Swing libraries provide for building GUIs in Java. This time we will look at several more GUI component topics. We

More information

Laborator 2 Aplicatii Java

Laborator 2 Aplicatii Java Laborator 2 Aplicatii Java Introducere in programarea vizuala - Pachetul AWT Scrieti, compilati si rulati toate exemplele din acest laborator: 1. import java.awt.*; class First extends Frame First() Button

More information