Building Java Programs Chapter 14 Graphical User Interfaces

Building Java Programs Chapter 14: Graphical User Interfaces Copyright 2006 by Pearson Education 1

Chapter outline n GUI basics n n n Laying out components n n Flow. Layout, Grid. Layout, and Border. Layout Additional components and events n n Graphical input and output with JOption. Pane Frames, buttons, labels, and text fields Changing a frame's layout Handling an action event Keyboard and mouse events 2 D graphics Copyright 2006 by Pearson Education 2

Graphical input and output with JOption. Pane reading: 14. 1 Copyright 2006 by Pearson Education 3

JOption. Pane An option pane is a simple dialog box for graphical input/output n advantages: n n simple flexible (in some ways) looks better than the black box of death disadvantages: n n created with static methods; not very object-oriented not very powerful (just simple dialog boxes) Copyright 2006 by Pearson Education 4

Types of JOption. Panes n n show. Message. Dialog(<parent>, <message>) Displays a message on a dialog with an OK button. show. Confirm. Dialog(<parent>, <message>) Displays a message and list of choices Yes, No, Cancel; returns user's choice as an int with one of the following values: n n JOption. Pane. YES_OPTION JOption. Pane. NO_OPTION JOption. Pane. CANCEL_OPTION show. Input. Dialog(<parent>, <message>) Displays a message and text field for input; returns the user's value entered as a String. n can pass null for the parent to all methods Copyright 2006 by Pearson Education 5

JOption. Pane examples 1 n show. Message. Dialog analogous to System. out. println for displaying a simple message import javax. swing. *; public class Message. Dialog. Example { public static void main(String[] args) { JOption. Pane. show. Message. Dialog(null, "How's the weather? "); JOption. Pane. show. Message. Dialog(null, "Second message"); } } Copyright 2006 by Pearson Education 6

JOption. Pane examples 2 n show. Confirm. Dialog analogous to a System. out. print that prints a question, then reading an input value from the user (can only be one of the provided choices) import javax. swing. *; public class Confirm. Dialog. Example { public static void main(String[] args) { int choice = JOption. Pane. show. Confirm. Dialog(null, "Erase your hard disk? "); if (choice == JOption. Pane. YES_OPTION) { JOption. Pane. show. Message. Dialog(null, "Disk erased!"); } else { JOption. Pane. show. Message. Dialog(null, "Cancelled. "); } } } Copyright 2006 by Pearson Education 7

JOption. Pane examples 3 n show. Input. Dialog analogous to a System. out. print that prints a question, then reading an input value from the user (can be any value) import javax. swing. *; public class Input. Dialog. Example { public static void main(String[] args) { String name = JOption. Pane. show. Input. Dialog(null, "What's yer name, pardner? "); JOption. Pane. show. Message. Dialog(null, "Yeehaw, " + name); } } Copyright 2006 by Pearson Education 8

Onscreen GUI elements n Most GUIs are not composed of option panes; they are too limited. Instead, complex GUIs contain the following elements: n n n frame: A graphical window on the screen. components: GUI widgets such as buttons or text fields in a frame. containers: Logical groups of components. Copyright 2006 by Pearson Education 9

JFrame example 1 n A simple program that creates and shows a JFrame: import javax. swing. *; public class Simple. Frame { public static void main(String[] args) { JFrame frame = new JFrame(); frame. set. Visible(true); } } n Graphical output: Copyright 2006 by Pearson Education 10

JFrame example 2 n A program that sets several properties of the JFrame: import java. awt. *; import javax. swing. *; public class Simple. Frame 2 { public static void main(String[] args) { JFrame frame = new JFrame(); frame. set. Foreground(Color. WHITE); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); frame. set. Location(new Point(10, 50)); frame. set. Size(new Dimension(300, 120)); frame. set. Title("A frame"); frame. set. Visible(true); } } n Graphical output: Copyright 2006 by Pearson Education 11

JFrame properties n JFrames have the following unique properties that you can get or set in your graphical programs: name type description methods default close operation int what should happen when frame is closed get. Default. Close. Operation, set. Default. Close. Operation icon image Image icon in the window's title bar get. Icon. Image, set. Icon. Image layout Layout. Manager how the frame should get. Layout, set. Layout resizable boolean whether the window can be resized is. Resizable, set. Resizable title String window's title bar text get. Title, set. Title position its components Copyright 2006 by Pearson Education 12

Component properties n All components also have the following properties: name type description methods background Color background color get. Background, set. Background enabled boolean whether the component can be interacted with is. Enabled, set. Enabled font Font font used to display any text on the component get. Font, set. Font foreground Color foreground color get. Foreground, set. Foreground location Point (x, y) position of component on screen get. Location, set. Location size Dimension width, height of component get. Size, set. Size preferred size Dimension width, height that the component wants to be get. Preferred. Size, set. Preferred. Size visible boolean whether the component can be seen on screen is. Visible, set. Visible Copyright 2006 by Pearson Education 13

Swing component hierarchy n Graphical components in Java form an inheritance hierarchy: java. lang. Object +--java. awt. Component +--java. awt. Container | +--javax. swing. JComponent | +--javax. swing. JButton | +--javax. swing. JLabel | +--javax. swing. JMenu. Bar | +--javax. swing. JOption. Pane | +--javax. swing. JPanel | +--javax. swing. JText. Area | +--javax. swing. JText. Field | +--java. awt. Window +--java. awt. Frame +--javax. swing. JFrame n When doing GUI programming, always import these packages: import java. awt. *; import javax. swing. *; Copyright 2006 by Pearson Education 14

Java GUI: AWT and Swing n Sun's initial idea: create a set of classes/methods that can be used to write a multi-platform GUI (Abstract Windowing Toolkit, or AWT) n n Second edition (JDK v 1. 2): Swing n n problem: not powerful enough; limited; a bit clunky to use a newer library written from the ground up that allows much more powerful graphics and GUI construction Drawback: Both exist in Java now; easy to get them mixed up; still have to use both sometimes! Copyright 2006 by Pearson Education 15

JFrame A frame is a graphical window that can be used to hold other components n public JFrame() public JFrame(String title) Creates a frame with an optional title. n public void set. Title(String text) Puts the given text in the frame’s title bar. n public void set. Default. Close. Operation(int op) Makes the frame perform the given action when it closes. Common value: JFrame. EXIT_ON_CLOSE n public void add(Component comp) Places the given component or container inside the frame. n n How would we add more than one component to the frame? NOTE: Call set. Visible(true) to make a frame appear on screen after creating it. Copyright 2006 by Pearson Education 16

JButton, JLabel The most common component— a button is a clickable onscreen region that the user interacts with to perform a single command A text label is simply a string of text displayed on screen in a graphical program. Labels often give information or describe other components n public JButton(String text) public JLabel(String text) Creates a new button / label with the given string as its text. n public String get. Text() Returns the text showing on the button / label. n public void set. Text(String text) Sets button / label's text to be the given string. Copyright 2006 by Pearson Education 17

JText. Field, JText. Area A text field is like a label, except that the text in it can be edited and modified by the user. Text fields are commonly used for user input, where the user types information in the field and the program reads it A text area is a multi-line text field n n public JText. Field(int columns) public JText. Area(int lines, int columns) Creates a new text field that is the given number of columns (letters) wide. n public String get. Text() Returns the text currently in the field. n public void set. Text(String text) Sets field's text to be the given string. Copyright 2006 by Pearson Education 18

Components example n The following program attempts to show two buttons: import java. awt. *; import javax. swing. *; public class Components. Example 1 { public static void main(String[] args) { JFrame frame = new JFrame(); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); frame. set. Size(new Dimension(300, 100)); frame. set. Title("A frame"); JButton button 1 = new JButton(); button 1. set. Text("I'm a button. "); button 1. set. Background(Color. BLUE); frame. add(button 1); JButton button 2 = new JButton(); button 2. set. Text("Click me!"); button 2. set. Background(Color. RED); frame. add(button 2); } frame. set. Visible(true); }Copyright 2006 by Pearson Education 19

Layout problems n n n The preceding program added two buttons to the frame, but only one appeared on the screen. layout manager: An object contained inside frames and other graphical containers that decides the position and size of the components inside the container. The default layout manager sizes each component added to occupy the full window space. Copyright 2006 by Pearson Education 20

Changing layouts n n We can correct the program's appearance by changing the frame's layout manager. Change the layout by calling the set. Layout method on the frame and passing a layout manager object. n n n We will see several layout managers later. We'll use one called a Flow. Layout, which sizes each component to its preferred size and positions them in left-to-right rows. If the following line is added to the preceding program just before calling set. Visible(true), its appearance will be: frame. set. Layout(new Flow. Layout()); Copyright 2006 by Pearson Education 21

Action events with Action. Listener reading: 14. 1 Copyright 2006 by Pearson Education 22

Event-driven Programming n n n program's execution is indeterminate on-screen components cause events to occur when they are clicked / interacted with events can be handled, causing the program to respond, driving the execution thru events (an "event-driven" program) Copyright 2006 by Pearson Education 23

Java Event Hierarchy java. lang. Object +--java. util. Event. Object +--java. awt. AWTEvent +--java. awt. event. Action. Event +--java. awt. event. Text. Event +--java. awt. event. Component. Event +--java. awt. event. Focus. Event +--java. awt. event. Window. Event +--java. awt. event. Input. Event +--java. awt. event. Key. Event +--java. awt. event. Mouse. Event n import java. awt. event. *; Copyright 2006 by Pearson Education 24

Action events: Action. Event n n n most common / simple event type in Swing represent an action occurring on a GUI component created by: n n n button clicks check box checking / unchecking menu clicks pressing Enter in a text field etc. Copyright 2006 by Pearson Education 25

Listening for events n n n attach listener to component listener’s appropriate method will be called when event occurs (e. g. when the button is clicked) for Action events, use Action. Listener Copyright 2006 by Pearson Education 26

Writing an Action. Listener // part of Java; you don't write this public interface Action. Listener { public void action. Performed(Action. Event event); } // Prints a message when the button is clicked. public class My. Action. Listener implements Action. Listener { public void action. Performed(Action. Event event){ JOption. Pane. show. Message. Dialog(null, "An event occurred!"); } } Copyright 2006 by Pearson Education 27

Attaching an Action. Listener JButton button = new JButton("button 1"); Action. Listener listener = new My. Action. Listener(); button. add. Action. Listener(listener); n now button will print "Event occurred!" when clicked n add. Action. Listener method exists in many Swing components Copyright 2006 by Pearson Education 28

Laying out components reading: 14. 2 Copyright 2006 by Pearson Education 29

Problem: positioning, resizing How does the programmer specify where each component sits in the window, how big each component should be, and what the component should do if the window is resized/moved/maximized/etc? n n Absolute positioning (C++, C#, others): Specify exact pixel coordinates for every component Layout managers (Java): Have special objects that decide where to position each component based on some criteria n What are benefits or drawbacks to each approach? Copyright 2006 by Pearson Education 30

Layout managers n Here are several common Java layout managers: Copyright 2006 by Pearson Education 31

Containers n n container: An object that holds components; it also governs their positions, sizes, and resizing behavior. Containers have the following public methods: n n public void add(Component comp) public void add(Component comp, Object info) Adds a component to the container, possibly giving extra information about where to place it. public void remove(Component comp) Removes the given component from the container. public void set. Layout(Layout. Manager mgr) Uses the given layout manager to position the components in the container. public void validate() You should call this if you change the contents of a container that is already on the screen, to make it re-do its layout. Copyright 2006 by Pearson Education 32

JPanel n A panel is our container of choice; it provides the methods from the previous slide and defines these additional methods (among others): n n public JPanel() Constructs a panel with a default flow layout. public JPanel(Layout. Manager mgr) Constructs a panel that uses the given layout manager. Copyright 2006 by Pearson Education 33

Preferred size of components n n n Swing component objects each have a certain size they would "like" to be--just large enough to fit their contents (text, icons, etc. ) This is called the preferred size of the component Some types of layout managers (e. g. Flow. Layout) choose to size the components inside them to the preferred size; others (e. g. Border. Layout, Grid. Layout) disregard the preferred size and use some other scheme Buttons at preferred size: Copyright 2006 by Pearson Education Not preferred size: 34

Flow. Layout public Flow. Layout() n n treats container as a left-to-right, top-to-bottom "page" or "paragraph" components are given their preferred size both horizontally and vertically components are positioned in order added if too long, components wrap around to next line Container panel = new JPanel(new Flow. Layout()); panel. add(new JButton("Button 1")); Copyright 2006 by Pearson Education 35

Flow. Layout example import java. awt. *; import javax. swing. *; public class Flow. Layout. Example { public static void main(String[] args) { JFrame frame = new JFrame(); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); frame. set. Size(new Dimension(320, 75)); frame. set. Title("Flow layout"); frame. set. Layout(new Flow. Layout()); frame. add(new JLabel("Type your ZIP Code: ")); frame. add(new JText. Field(5)); frame. add(new JButton("Submit")); } } frame. set. Visible(true); Copyright 2006 by Pearson Education 36

Grid. Layout public Grid. Layout(int rows, int columns) n n n treats container as a grid of equally-sized rows and columns components are given equal horizontal / vertical size, disregarding preferred size can specify 0 rows or columns to indicate expansion in that direction as needed Copyright 2006 by Pearson Education 37

Grid. Layout example import java. awt. *; import javax. swing. *; public class Grid. Layout. Example { public static void main(String[] args) { JFrame frame = new JFrame(); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); frame. set. Size(new Dimension(300, 120)); frame. set. Title("The grid"); } } // 2 rows, 3 columns frame. set. Layout(new Grid. Layout(2, 3)); for (int i = 1; i <= 6; i++) { JButton button = new JButton(); button. set. Text("Button " + i); frame. add(button); } frame. set. Visible(true); Copyright 2006 by Pearson Education 38

Border. Layout public Border. Layout() n n divides container into five regions: NORTH, SOUTH, WEST, EAST, CENTER NORTH and SOUTH regions expand to fill region horizontally, and use preferred size vertically WEST and EAST regions expand to fill region vertically, and use preferred size horizontally CENTER uses all space not occupied by others Container panel = new JPanel(new Border. Layout()); panel. add(new JButton("Button 1 (NORTH)", Border. Layout. NORTH); Copyright 2006 by Pearson Education 39

Border. Layout example import java. awt. *; import javax. swing. *; public class Border. Layout. Example { public static void main(String[] args) { JFrame frame = new JFrame(); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); frame. set. Size(new Dimension(210, 200)); frame. set. Title("Run for the border"); frame. set. Layout(new Border. Layout()); frame. add(new JButton("north"), Border. Layout. NORTH); frame. add(new JButton("south"), Border. Layout. SOUTH); frame. add(new JButton("west"), Border. Layout. WEST); frame. add(new JButton("east"), Border. Layout. EAST); frame. add(new JButton("center"), Border. Layout. CENTER); } } frame. set. Visible(true); Copyright 2006 by Pearson Education 40

Box. Layout Box. create. Horizontal. Box() Box. create. Vertical. Box() n n n aligns components in container in a single row or column components use preferred sizes and align based on their preferred alignment preferred way to construct a container with box layout: Box. create. Horizontal. Box(); or Box. create. Vertical. Box(); Copyright 2006 by Pearson Education 41

Other layouts n Card. Layout layers of "cards" stacked on top of each other; one visible at a time n Grid. Bag. Layout very complicated; recommendation: never use it! Copyright 2006 by Pearson Education 42

Complex layouts n How would you create a complex window like this, using the layout managers shown? Copyright 2006 by Pearson Education 43

Solution: composite layout n n n create panels within panels each panel has a different layout, and by combining the layouts, more complex / powerful layout can be achieved example: n n how many panels? what layout in each? Copyright 2006 by Pearson Education 44

Composite layout example import java. awt. *; import javax. swing. *; public class Telephone { public static void main(String[] args) { JFrame frame = new JFrame(); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); frame. set. Size(new Dimension(250, 200)); frame. set. Title("Telephone"); frame. set. Layout(new Border. Layout()); JPanel center. Panel = new JPanel(new Grid. Layout(4, 3)); for (int i = 1; i <= 9; i++) { center. Panel. add(new JButton("" + i)); } center. Panel. add(new JButton("*")); center. Panel. add(new JButton("0")); center. Panel. add(new JButton("#")); frame. add(center. Panel, Border. Layout. CENTER); JPanel south. Panel = new JPanel(new Flow. Layout()); south. Panel. add(new JLabel("Number to dial: ")); south. Panel. add(new JText. Field(10)); frame. add(south. Panel, Border. Layout. SOUTH); } } frame. set. Visible(true); Copyright 2006 by Pearson Education 45

Additional components reading: 14. 4 Copyright 2006 by Pearson Education 46

JCheck. Box, JRadio. Button A check box is a toggleable button with two states: checked and unchecked A radio button is a button that can be selected; usually part of a group of mutuallyexclusive radio buttons (1 selectable at a time) n public JCheck. Box / JRadio. Button(String text) public JCheck. Box(String text, boolean is. Checked) Creates checked/unchecked check box with given text. n public boolean is. Selected() Returns true if check box is checked. n public void set. Selected(boolean selected) Sets box to be checked/unchecked. Copyright 2006 by Pearson Education 47

Button. Group A logical group of radio buttons that ensures that only one is selected at a time n n n public Button. Group() public void add(JRadio. Button button) The Button. Group is not a graphical component, just a logical group; the Radio. Buttons themselves are added to the container, not the Button. Group Copyright 2006 by Pearson Education 48

Image. Icon Allows you to put a picture on a button, label or other component n public class Image. Icon implements Icon n public Image. Icon(String filename) public Image. Icon(URL address) in JButton, JRadio. Button, JCheck. Box, JLabel, etc. . . n n constructor that takes an Icon public void set. Icon(Icon) public void set. Selected. Icon(Icon) public void set. Rollover. Icon(Icon) Copyright 2006 by Pearson Education 49

JScroll. Pane A special container that holds a component, using scrollbars to allow that component to be seen n public JScroll. Pane(Component comp) Wraps the given component with scrollbars. After constructing the scroll pane, add the scroll pane to the container, not the original component. frame. add(new JScroll. Pane(area), Border. Layout. CENTER); Copyright 2006 by Pearson Education 50

JFile. Chooser A special dialog box that allows the user to select one or more files/folders n n n public JFile. Chooser() public JFile. Chooser(String current. Dir) public int show. Open. Dialog(Component parent) public int show. Save. Dialog(Component parent) public File get. Selected. File() public static int APPROVE_OPTION, CANCEL_OPTION Possible result values from show. Xxx. Dialog(. . ). JFile. Chooser chooser = new JFile. Chooser(); int result = chooser. show. Save. Dialog(this); if (result == JFile. Chooser. APPROVE_OPTION) this. save. Data(chooser. get. Selected. File(). get. Name()); Copyright 2006 by Pearson Education 51

JColor. Chooser Another special dialog that lets the user pick from a palette of colors n n n public JColor. Chooser() public JColor. Chooser(Color initial) public Color show. Dialog(Component parent, String title, Color initial. Color) n returns null if user chose Cancel option Copyright 2006 by Pearson Education 52

Even more additional components Copyright 2006 by Pearson Education 53

JMenu. Bar The top-level container that holds menus; can be attached to a frame n n public JMenu. Bar() public void add(JMenu menu) Usage: in JFrame, the following method exists: n public void set. JMenu. Bar(JMenu. Bar bar) Copyright 2006 by Pearson Education 54

JMenu A menu to hold menu items; menus can contain other menus n public JMenu(String text) n public void add(JMenu. Item item) public void add. Separator() public void set. Mnemonic(int mnemonic) n n Copyright 2006 by Pearson Education 55

JMenu. Item An entry in a frame's Menu bar, which can be clicked to perform commands n n n n public JMenu. Item(String text) public JMenu. Item(String text, Icon icon) public JMenu. Item(String text, int mnemonic) public void add. Action. Listener( Action. Listener al) public void set. Accelerator(Key. Stroke ks) public void set. Enabled(boolean b) public void set. Mnemonic(int mnemonic) Copyright 2006 by Pearson Education 56

JCheck. Box. Menu. Item, JRadio. Button. Menu. Item Radio button and checkbox-like menu items n n n n public Icon public J_____Menu. Item(String text) J_____Menu. Item(String text, boolean select) J_____Menu. Item(String text, Icon icon) J_____Menu. Item(String text, icon, boolean selected) void add. Action. Listener(Action. Listener al) boolean is. Selected() void set. Selected(boolean b) Recall: in a Button. Group, the following method exists: n public void add(Abstract. Button button) These two classes extend Abstract. Button! Copyright 2006 by Pearson Education 57

Mnemonics n n mnemonic: menu hotkey assigned to a button or other graphical component usually visible as an underlined key, activated by pressing Ctrl+key (buttons) or Alt+key (menus) only work when input focus is on the appropriate component (affects menus) usage: call set. Mnemonic(char) method n menu items also have constructor that takes mnemonic my. Quit. Button. set. Mnemonic('Q'); JMenu. Item my. New. Item = new JMenu. Item("New", 'N'); // or, my. New. Item. set. Mnemonic('N'); Copyright 2006 by Pearson Education 58

Accelerators n accelerator: global hotkey combination that performs an action (ex: Alt-X to exit program) even on components that aren't in focus / visible n n n can be run at any time in the application can optionally include modifiers like Shift, Alt created by calling the get. Key. Stroke method of the Key. Stroke class, and passing this to set. Accelerator method of various components (buttons, menus) menu. Item. set. Accelerator( Key. Stroke. get. Key. Stroke('T', Key. Event. ALT_MASK)); Copyright 2006 by Pearson Education 59
![JCombo. Box n n n public JCombo. Box() public JCombo. Box(Object[] items) public JCombo. JCombo. Box n n n public JCombo. Box() public JCombo. Box(Object[] items) public JCombo.](http://slidetodoc.com/presentation_image_h/9e7d7344aad0214a048f4c8db103bbdc/image-60.jpg)
JCombo. Box n n n public JCombo. Box() public JCombo. Box(Object[] items) public JCombo. Box(Vector items) public JCombo. Box(Combo. Box. Model model) Constructs a combo box. Can optionally pass a vector or model of items. (See Default. Combo. Box. Model for a model implementation. ) public void add. Action. Listener( Action. Listener al) Causes an action event to be sent to listener al when the user selects or types a new item in the combo box. Copyright 2006 by Pearson Education 60

JCombo. Box: Managing Items n public void add. Item(Object item) n public Object get. Item. At(int index) n public void remove. All. Items() public void remove. Item(Object item) public void remove. Item. At(int index) n n Copyright 2006 by Pearson Education 61

JCombo. Box: Selected Item n n public int get. Selected. Index() public Object get. Selected. Item() n public void set. Selected. Item(Object item) public void set. Selected. Index(int index) n public void set. Enabled(boolean enabled) n public void set. Editable(boolean editable) If editable, the user can type new arbitrary values into the combo box. n Copyright 2006 by Pearson Education 62

JTabbed. Pane A container that can hold many "tab" subcontainers, each with components in it n n n public JTabbed. Pane() public JTabbed. Pane(int tab. Alignment) Constructs a new tabbed pane. Defaults to having the tabs on top; can be set to JTabbed. Pane. BOTTOM, LEFT, RIGHT, etc. public void Component add. Tab(String title, Component comp) add. Tab(String title, Icon icon, comp, String tooltip) Adds the given component as a tab in this tabbed pane. Can optionally use an icon and/or tool tip. Copyright 2006 by Pearson Education 63

JTabbed. Pane methods n public void insert. Tab(String title, Icon icon, Component comp, String tooltip, int index) n n public void remove(Component comp) public void remove(int index) public void remove. All() n public void set. Selected. Component(Component c) n public void set. Selected. Index(int index) n Copyright 2006 by Pearson Education 64

JSplit. Pane A container that can hold two components, divided by a movable separator n n n public JSplit. Pane() public JSplit. Pane(int orientation) Constructs a new tabbed pane. Defaults to having a horizontal split; can be set to JSplit. Pane. HORIZONTAL_SPLIT, VERTICAL_SPLIT, etc. public void set. Bottom. Component(Component comp) set. Left. Component(Component comp) set. Right. Component(Component comp) set. Top. Component(Component comp) Sets the given component to occupy the desired region of the split pane. Copyright 2006 by Pearson Education 65

JTool. Bar A movable container to hold common buttons, commands, etc n n n public JTool. Bar() public JTool. Bar(int orientation) public JTool. Bar(String title, int orientation) Constructs a new tool bar, optionally with a title and orientation; can be JTool. Bar. HORIZONTAL or VERTICAL, defaults to horizontal public void add(Component comp) Adds the given component to this tool bar's horizontal/vertical flowing layout. Copyright 2006 by Pearson Education 66

JTool. Bar: Usage n n n construct toolbar add items (usually buttons) to toolbar add toolbar to edge of Border. Layout of content pane (usually NORTH) n don't put anything in other edges (N/S/E/W)! Copyright 2006 by Pearson Education 67

JList A list of selectable pre-defined items n public JList() Constructs an empty JList. n public JList(List. Model model) public JList(Object[] data) public JList(Vector data) Constructs a JList that displays the given data. n n n public void add. List. Selection. Listener( List. Selection. Listener lsl) Adds the given listener to be informed when the selected index / indices change for this list. Copyright 2006 by Pearson Education 68

JList: more methods n public void clear. Selection() n public int get. Selected. Index() public int[] get. Selected. Indices() n n n public Object get. Selected. Value() public Object[] get. Selected. Values() public void set. Selected. Index(int index) public void set. Selected. Indices(int[] indices) Methods for getting / setting the selected item and index in the list. Copyright 2006 by Pearson Education 69

JList: even more methods n n n public Causes List. Model get. Model() void set. List. Data(Object[] data) void set. List. Data(Vector data) void set. Model(List. Model model) this list to now display the given collection of data. public int get. Selection. Mode() public void set. Selection. Mode(int mode) Get / set selection mode for the list. For example, set to List. Selection. Model. SINGLE_SELECTION to only allow one item in the list to be chosen at once. SINGLE_SELECTION SINGLE_INTERVAL_SELECTION MULTIPLE_INTERVAL_SELECTION Copyright 2006 by Pearson Education 70

JDialog A window that is a child of the overall JFrame; used for popup windows, option/config boxes, etc. n n public JDialog(Dialog parent, boolean modal) public JDialog(Frame parent, String title, boolean modal) Constructs a new dialog with the given parent and title. If the modal flag is set, this dialog is a child of the parent and the parent will be locked until the dialog is closed. public void show() Shows this dialog on screen. If the dialog is modal, calling show() will lock the parent frame/dialog. JDialog has most all JFrame methods: get. Content. Pane(), set. JMenu. Bar(JMenu. Bar), set. Resizable(boolean), set. Title(String), . . . Copyright 2006 by Pearson Education 71

Some eye candy. . . n making a Java Swing GUI look like the native operating system: try { UIManager. set. Look. And. Feel( UIManager. get. System. Look. And. Feel. Class. Name()); } catch Exception e) {} n adding borders to components: whatever. Component. set. Border( Border. Factory. create. Line. Border(Color. BLUE, 3)); Copyright 2006 by Pearson Education 72

Mouse and keyboard events reading: 14. 4 Copyright 2006 by Pearson Education 73

Mouse events n Uses of mouse events: n n n listen to clicks and movement of mouse within a GUI component (usually a panel) respond to mouse activity with appropriate actions create interactive programs that are driven by mouse activity Copyright 2006 by Pearson Education 74

Listening to clicks: Mouse. Listener package java. awt. event; public interface Mouse. Listener { public void mouse. Clicked(Mouse. Event event); public void mouse. Entered(Mouse. Event event); public void mouse. Exited(Mouse. Event event); public void mouse. Pressed(Mouse. Event event); public void mouse. Released(Mouse. Event event); } Copyright 2006 by Pearson Education 75

Mouse. Listener example public class My. Mouse. Listener implements Mouse. Listener { public void mouse. Clicked(Mouse. Event event) {} public void mouse. Entered(Mouse. Event event) {} public void mouse. Exited(Mouse. Event event) {} public void mouse. Pressed(Mouse. Event event) { System. out. println("User pressed mouse button!"); } public void mouse. Released(Mouse. Event event) {} } Copyright 2006 by Pearson Education 76

Mouse. Listener usage // assumes some custom panel class named My. Panel panel = new My. Panel(); panel. add. Mouse. Listener(new My. Mouse. Listener()); n Problem: Tedious to implement entire interface when only partial behavior is wanted/needed Copyright 2006 by Pearson Education 77

Mouse. Adapter n n an abstract class with empty implementations of all Mouse. Listener methods usage: extend Mouse. Adapter and override the methods you want to do something removes need for you to type in empty methods for all the ones you don’t want an example of the Adapter design pattern Copyright 2006 by Pearson Education 78

Mouse. Adapter usage public class My. Mouse. Adapter extends Mouse. Adapter { public void mouse. Pressed(Mouse. Event event) { System. out. println("User pressed mouse button!"); } }. . . // using the My. Mouse. Adapter My. Panel panel = new My. Panel(); panel. add. Mouse. Listener(new My. Mouse. Adapter()); Copyright 2006 by Pearson Education 79

Mouse. Event objects n Input. Event n n Mouse. Event n n n public static int BUTTON 1_MASK, BUTTON 2_MASK, BUTTON 3_MASK, CTRL_MASK, ALT_MASK, SHIFT_MASK public int get. Click. Count() public Point get. Point() public int get. X(), get. Y() public Object get. Source() public int get. Modifiers() (use the above button masks with this) Swing. Utilities n n is. Left. Mouse. Button(Mouse. Event event) is. Right. Mouse. Button(Mouse. Event event) Copyright 2006 by Pearson Education 80

Mouse. Event: usage public class My. Mouse. Adapter extends Mouse. Adapter { public void mouse. Pressed(Mouse. Event event) { Point p = event. get. Point(); Object source = event. get. Source(); if (source == this. panel && p. get. X() < 10) { JOption. Pane. show. Message. Dialog(null, "You clicked the left side of my. Panel!"); } } } Copyright 2006 by Pearson Education 81

Mouse movement: Mouse. Motion. Listener package java. awt. event; public interface Mouse. Motion. Listener { public void mouse. Dragged(Mouse. Event event); public void mouse. Moved(Mouse. Event event); } n abstract Mouse. Motion. Adapter class provides empty implementations of both methods if you just want to override one Copyright 2006 by Pearson Education 82

Mouse. Motion. Adapter example public class My. Mouse. Motion. Adapter extends Mouse. Motion. Adapter { public void mouse. Moved(Mouse. Event event) { Point p = event. get. Point(); double x = event. get. X(); double y = event. get. Y(); System. out. println("Mouse is at " + p); System. out. println("x is " + x); System. out. println("y is " + y); } } // using the listener my. Panel. add. Mouse. Motion. Listener(new My. Mouse. Motion. Adapter()); Copyright 2006 by Pearson Education 83

Mouse. Input. Listener package javax. swing. event; public interface Mouse. Input. Listener extends Mouse. Listener, Mouse. Motion. Listener {} n more importantly: Mouse. Input. Adapter class includes empty implementations for ALL methods from both mouse input interfaces, allowing same listener to listen to mouse clicks and movement Copyright 2006 by Pearson Education 84

Mouse. Input. Adapter: Example public class My. Mouse. Input. Adapter extends Mouse. Input. Adapter { public void mouse. Pressed(Mouse. Event event) { System. out. println("Mouse was pressed"); } public void mouse. Moved(Mouse. Event event) { Point p = event. get. Point(); System. out. println("Mouse is at " + p); } }. . . // using the listener My. Mouse. Input. Adapter adapter = new My. Mouse. Input. Adapter(); my. Panel. add. Mouse. Listener(adapter); my. Panel. add. Mouse. Motion. Listener(adapter); Copyright 2006 by Pearson Education 85

Keyboard Events n Usage of keyboard events: n n n listen to keyboard activity within a GUI component (usually a panel) respond to keyboard activity with appropriate actions control onscreen drawn characters and simulate text input Copyright 2006 by Pearson Education 86

Key Presses: Key. Listener package java. awt. event; public interface Key. Listener { public void key. Pressed(Key. Event event); public void key. Released(Key. Event event); public void key. Typed(Key. Event event); } n abstract class Key. Adapter implements all Key. Listener methods Copyright 2006 by Pearson Education 87

Key. Event objects n Input. Event n n public static int CTRL_MASK, ALT_MASK, SHIFT_MASK Key. Event n n n public static int VK_A. . VK_Z, VK_0. . VK_9, VK_F 1. . VK_F 10, VK_UP, VK_LEFT, . . , VK_TAB, VK_SPACE, VK_ENTER, . . . (one for every key) public char get. Key. Char() public int get. Key. Code() public Object get. Source() public int get. Modifiers() (use masks with this) Copyright 2006 by Pearson Education 88

Key. Adapter example class Pac. Man. Key. Listener extends Key. Adapter { public void key. Pressed(Key. Event event) { char key. Char = event. get. Key. Char(); int key. Code = event. get. Key. Code(); if (key. Code == Key. Event. VK_RIGHT) { pacman. set. X(pacman. get. X() + 1); pacpanel. repaint(); } else if (key. Char == 'Q') { System. exit(0); } } } // assumes some custom panel class named Pac. Panel panel = new Pac. Panel(); panel. add. Key. Listener(new Pac. Key. Listener()); Copyright 2006 by Pearson Education 89

Other kinds of events n Window. Listener/Adapter/Event: Responds to events in a top-level window (JFrame). Useful to catch window. Closing event and respond, e. g. prompt to save current file n Focus. Listener/Event: Responds to when the keyboard focus changes to a different component. Useful to validate input format on a text field. n List. Selection. Listener, Hyperlink. Listener, Item. Listener: Event listeners for specific Swing components (JList, JEditor. Pane, JCombo. Box respectively) Copyright 2006 by Pearson Education 90

2 D Graphics reading: 14. 5 Copyright 2006 by Pearson Education 91

A drawing panel n extend JPanel and override paint. Component method to use a panel as a drawing surface public void paint. Component(Graphics g) n n coordinate system: (0, 0) at top-left, x-axis increases rightward, y-axis downward panel surface is transparent unless drawn on Copyright 2006 by Pearson Education 92

Some details n n JPanel's paint. Component does important things that we don't want to lose, so call the method super. paint. Component first thing! paint. Component's Graphics g argument represents "graphical context" object that can be told to draw things on the panel n n n Guaranteed for every JPanel that actual object passed in is a Graphics 2 D (can cast) panel has small preferred size, so it will be tiny when put into some layouts; use set. Preferred. Size(Dimension) to make it bigger! refreshing panel: can't call paint. Component, so call repaint() Copyright 2006 by Pearson Education 93

Basic panel painting syntax public class My. Panel extends JPanel { public void paint. Component(Graphics g) { super. paint. Component(g); // important! // put your painting code here } } Copyright 2006 by Pearson Education 94

Quick drawing example public class My. Panel extends JPanel { public My. Panel() { this. set. Background(Color. WHITE); } public void paint. Component(Graphics g) { super. paint. Component(g); g 2. set. Color(Color. BLUE); g. fill. Oval(10, 20, 50); } } Copyright 2006 by Pearson Education 95

Drawing text strings Graphics n public void draw. String(String s, int x, int y) Draws given string with its first letter's bottom-left corner at the given location. n n The string is drawn using the Graphics' current color and font settings. Before drawing the string, you can set the font, color, and other attributes. (see next slides) Copyright 2006 by Pearson Education 96

Fonts Graphics n public void set. Font(Font f) Sets this Graphics context to start writing text in the given font. (Forgotten at end of paint. Component call!) n java. awt. Font Text styles used when drawing Strings on the panel n public Font(String name, int style, int size) n some predefined font names: n n "Serif", "Sans. Serif", "Monospaced" font styles (can be combined with + operator): n n n Font. BOLD Font. ITALIC Font. PLAIN Copyright 2006 by Pearson Education 97

Colors and paints n java. awt. Color (a simple single-colored paint) n n public Color(int r, int g, int b) public Color(int r, int g, int b, int alpha) n n n a partially-transparent color (range 0 -255, 0=transparent) public Color brighter(), darker() public static Color BLACK, BLUE, CYAN, DARK_GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW Copyright 2006 by Pearson Education 98

Drawing shapes Graphics n public n public n public. . . void void void draw. Line(int x 1, int y 1, int x 2, int y 2) draw. Oval(int x, int y, int w, int h) fill. Oval(int x, int y, int w, int h) draw. Polygon(int[] xpoints, int[] ypoints, int len) fill. Polygon(int[] xpoints, int[] ypoints, int len) draw. Rect(int x, int y, int w, int h) fill. Rect(int x, int y, int w, int h) draw. Arc(. . . ) fill. Arc(. . . ) Copyright 2006 by Pearson Education 99

Drawing images Graphics n public void draw. Image(Image i, int x, int y, Image. Observer io) n public void draw. Image(Image i, int x, int y, int width, int height, Image. Observer io) Draws given image with this Graphics pen with its top-left corner at given location (pass the panel as the Image. Observer). Copyright 2006 by Pearson Education 100

Classes for imaging n java. awt. Toolkit Gets images from disk or internet n n java. awt. Media. Tracker Ensures that images are loaded fully n n public Media. Tracker(Component comp) public void add. Image(Image img, int id) public void wait. For. All() throws Interrupted. Exception java. awt. Image Represents a graphic image (BMP, GIF, . . . ) n n n public static Toolkit get. Default. Toolkit() public Image get. Image(String filename) public Image get. Image(URL address) public int get. Width(Image. Observer obs) public int get. Height(Image. Observer obs) java. awt. image. Buffered. Image A blank graphic image surface onto which you can draw n n public Buffered. Image(int w, int h, int type) public Graphics get. Graphics() Copyright 2006 by Pearson Education 101

Images, continued n Code to load an image: Toolkit tk = Toolkit. get. Default. Toolkit(); Image img = tk. get. Image("myimage. jpg"); Media. Tracker mt = new Media. Tracker(this); mt. add. Image(img, 0); // any ID will do try { mt. wait. For. All(); } catch (Interrupted. Exception ie) {} n This is tedious! n suggest making a helper method to load and return one image public Image load. Image(String filename) Copyright 2006 by Pearson Education 102

Animation with Timers reading: 14. 5 Copyright 2006 by Pearson Education 10 3

Timers—Why? n n execute an action multiple times at given intervals create animations in our GUI programs add delays and pauses when required / desired a Timer is an example of a "callback" -- your code starts the timer, then later at a specified time, the timer activates, causing an event in your system Copyright 2006 by Pearson Education 104

javax. swing. Timer n public Timer(int ms_delay, Action. Listener al) Causes al to fire an action. Performed every ms_delay milliseconds. n public void start() Causes timer to begin ticking; the first tick happens after the initial delay, and the rest occur separated by the timer's delay. n public void stop() Stops timer from ticking. n public void restart() Restarts timer, causing it to wait its initial delay and then begin firing at its delay rate. Copyright 2006 by Pearson Education 105

Timer: more methods n public void add. Action. Listener(Action. Listener a) Adds additional listeners to be fired as the timer ticks. n public boolean is. Running() Returns true when timer is ticking (has been started). n public void set. Delay(int delay) Changes the delay between timer ticks. n public void set. Initial. Delay(int delay) Sets a one-time delay to occur before ticking starts. n public void set. Repeats(boolean b) Set to false to make timer fire only once. Copyright 2006 by Pearson Education 106

Timer example // This code could be used to move a shape to the right // across the screen. int DELAY = 100; Action. Listener updater = new Action. Listener() { public void action. Performed(Action. Event event) { x++; my. Panel. repaint(); } } Timer tim = new Timer(DELAY, updater); tim. start(); Copyright 2006 by Pearson Education 107
- Slides: 107