Object Oriented Programming

Similar documents
Graphical User Interfaces. Comp 152

Introduction to the JAVA UI classes Advanced HCI IAT351

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

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!

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

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

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

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

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

Part I: Learn Common Graphics Components

CS 251 Intermediate Programming GUIs: Components and Layout

Summary Chapter 25 GUI Components: Part 2

Window Interfaces Using Swing Objects

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Chapter 6: Graphical User Interfaces

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

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

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

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

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

To gain experience using GUI components and listeners.

BASICS OF GRAPHICAL APPS

Window Interfaces Using Swing Objects

Lecture 18 Java Graphics and GUIs

Swing. By Iqtidar Ali

Programming graphics

Java Programming Lecture 6

Introduction p. 1 JFC Architecture p. 5 Introduction to JFC p. 7 The JFC 1.2 Extension p. 8 Swing p. 9 Drag and Drop p. 16 Accessibility p.

More Swing. Chapter 14. Chapter 14 1

Introduction. Introduction

Chapter 12 GUI Basics

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

Swing/GUI Cheat Sheet

Chapter 7: A First Look at GUI Applications

Tool Kits, Swing. Overview. SMD158 Interactive Systems Spring Tool Kits in the Abstract. An overview of Swing/AWT

Chapter 14. More Swing

CSE 331 Software Design & Implementation

Swing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Java Swing. Lists Trees Tables Styled Text Components Progress Indicators Component Organizers

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Chapter 12 Advanced GUIs and Graphics

Java IDE Programming-I

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

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

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

PIC 20A GUI with swing

Graphical User Interface (GUI)

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

Systems Programming Graphical User Interfaces

Unit 6: Graphical User Interface

Advanced Java Programming. Swing. Introduction to Swing. Swing libraries. Eran Werner, Tel-Aviv University Summer, 2005

Building Graphical User Interfaces. GUI Principles

Sri Vidya College of Engineering & Technology

CS111: PROGRAMMING LANGUAGE II

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

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

Object-Oriented Programming Design. Topic : User Interface Components with Swing GUI Part III

Outline CSE 3461 F10. What is a Widget? Properties of Widgets. A self-contained screen object Also called a control Examples of widgets:

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

Window Interfaces Using Swing. Chapter 12

Java. GUI building with the AWT

Containers and Components

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

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

Building Graphical User Interfaces. Overview

2110: GUIS: Graphical User Interfaces

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

Announcements. Introduction. Lecture 18 Java Graphics and GUIs. Announcements. CSE 331 Software Design and Implementation

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

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

Widgets. Widgets Widget Toolkits. User Interface Widget

Agenda. Container and Component

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

WIMP Elements. GUI goo. What is WIMP?

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

Chapter 17 Creating User Interfaces

Basicsof. JavaGUI and SWING

Widgets. Widgets Widget Toolkits. 2.3 Widgets 1

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

Graphical User Interface (GUI)

Contents Chapter 1 Introduction to Programming and the Java Language

Graphical User Interface (Part-3) Supplementary Material for CPSC 233

Graphical Applications

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

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

Object Oriented Design & Patterns. Part 1

Layout. Dynamic layout, Swing and general layout strategies

Laying Out Components. What is Widget Layout?

INTRODUCTION TO (GUIS)

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

Design patterns for graphical user interface applications

Graphical User Interface (GUI)

Chapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place.

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

Java continued. Chapter 8 ALERT ALERT. Last week. MCQ test next week. This time. This place. Closed book. Assignment #2 is for groups of 3

Java: Graphical User Interfaces (GUI)

GUI Event Handlers (Part II)

Chapter 18. Advanced graphics programming

Dr. Hikmat A. M. AbdelJaber

Transcription:

Object Oriented Programming 1. Graphical User Interfaces OOP10 - M. Joldoş - T.U. Cluj 1

GUI A Graphical User Interface (GUI pronounced "goo-ee") presents a userfriendly mechanism for interacting with a program Gives a program a distinctive "look" and "feel" Allows users to be somewhat familiar with a program before they ever use it Reduces the time to learn usage OOP10 - M. Joldoş - T.U. Cluj 2

Containers and Components (again) Class Component declares the common attributes and behaviors of all its subclasses Important methods: paint(), repaint() Class Container manages a collection of related components In applications with JFrame and in applets we attach components to the content pane a container Important methods: add(), setlayout() OOP10 - M. Joldoş - T.U. Cluj 3

The Container Class Any class that is a descendent class of the class Container is considered to be a container class The Container class is found in the java.awt package, not in the Swing library Any object that belongs to a class derived from the Container class (or its descendents) can have components added to it The classes JFrame and JPanel are descendent classes of the class Container Therefore they and any of their descendents can serve as a container OOP10 - M. Joldoş - T.U. Cluj 4

The JComponent Class Declares common attributes and behaviors for its subclasses, such as: a pluggable look-and-feel used to customize the appearance of components shortcut keys for direct access to GUI components through the keyboard common event-handling capabilities for cases where several GUI components initiate the same actions in a program brief descriptions of a GUI's component purpose (called tool tips) OOP10 - M. Joldoş - T.U. Cluj 5

The JComponent Class Provides support for user interface localizationcustomizing the interface to display in different language and use local cultural conventions Any descendent class of the class JComponent is called a component class Any JComponent object or component can be added to any container class object Because it is derived from the class Container, a JComponent can also be added to another JComponent OOP10 - M. Joldoş - T.U. Cluj 6

Swing and the Model-View-Controller Architecture Swing architecture is rooted in the model-view-controller (MVC) design that dates back to SmallTalk. MVC architecture calls for a visual application to be broken up into three separate parts: A model that represents internally the data for the application The view that is the visual representation of that data. A controller that takes user input on the view and translates that to changes in the model. OOP10 - M. Joldoş - T.U. Cluj 7

The Model Most programs are supposed to do work, not just be another pretty face but there are some exceptions useful programs existed long before GUIs The Model is the part that does the work it models the actual problem being solved The Model should be independent of both the Controller and the View But it can provide services (methods) for them to use Independence gives flexibility, robustness OOP10 - M. Joldoş - T.U. Cluj 8

The Controller The Controller decides what the model is to do Often, the user is put in control by means of a GUI in this case, the GUI and the Controller are often the same The Controller and the Model can almost always be separated (what to do versus how to do it) The design of the Controller depends on the Model The Model should not depend on the Controller OOP10 - M. Joldoş - T.U. Cluj 9

The View Typically, the user has to be able to see, or view, what the program is doing The View shows what the Model is doing The View is a passive observer; it should not affect the model The Model should be independent of the View, but (but it can provide access methods) The View should not display what the Controller thinks is happening OOP10 - M. Joldoş - T.U. Cluj 10

Combining Controller and View Sometimes the Controller and View are combined, especially in small programs Combining the Controller and View is appropriate if they are very interdependent The Model should still be independent Never mix Model code with GUI code! OOP10 - M. Joldoş - T.U. Cluj 11

Separation of concerns As always, you want code independence The Model should not be contaminated with control code or display code The View should represent the Model as it really is, not some remembered status The Controller should talk to the Model and View, not manipulate them The Controller can set variables that the Model and View can read OOP10 - M. Joldoş - T.U. Cluj 12

Swing Separable Model Architecture The view and controller parts of a component required a tight coupling These two entities were collapsed into a single UI (userinterface) object This new quasi-mvc design is sometimes referred to a separable model architecture. OOP10 - M. Joldoş - T.U. Cluj 13

Containment Hierarchies Top level containers Intermediate containers Atomic components Top level containers: At the root of every containment hierarchy All Swing programs have at least one Content panes Types of top-level containers Frames Dialogs Applets OOP10 - M. Joldoş - T.U. Cluj 14

Dialog boxes More limited than frames Modality Modal dialog boxes temporarily halt the program the user cannot continue until the dialog has been closed Types of dialogs JOptionPane ProgressMonitor JColorChooser JDialog OOP10 - M. Joldoş - T.U. Cluj 15

Showing dialogs JOptionPane.showXYZDialog( ) Option and Message dialogs JOptionPane.showMessageDialog(frame, Error!, An error message, JOptionPane.ERROR_MESSAGE); JOptionPane.showOptionDialog(frame, Save?, A save dialog, JOptionPane.YES_NO_CANCEL_OPTION); Input, Confirm Customization showoptiondialog - Fairly customizable JDialog - Totally customizable OOP10 - M. Joldoş - T.U. Cluj 16

Intermediate containers Panels (or panes ) Root panes The content pane Layered panes Glass panes OOP10 - M. Joldoş - T.U. Cluj 17

Root panes Invisibly attached to top-level container Created by Swing on realizing frame Manages everything between top-level container and components Places menu bar and content pane in an instance of JLayeredPane OOP10 - M. Joldoş - T.U. Cluj 18

JLayeredPanes depth OOP10 - M. Joldoş - T.U. Cluj 19

Content panes Usually use a JPanel Contains everything except menu bar for most Swing applications Can be explicitly, or implicitly created, simplified code //Create a panel and add components to it. JPanel contentpane = new JPanel(); contentpane.add(somecomponent); contentpane.add(anothercomponet); //Make it the content pane. contentpane.setopaque(true); toplevelcontainer.setcontentpane(contentpane) ; OOP10 - M. Joldoş - T.U. Cluj 20

Glass panes Not structured into components event catching painting Used for weird interface behavior, rarely used. Either created explicitly or root version used OOP10 - M. Joldoş - T.U. Cluj 21

Objects in a Typical GUI Almost every GUI built using Swing container classes will be made up of three kinds of objects: 1. The container itself, probably a panel or window-like object 2. The components added to the container such as labels, buttons, and panels 3. A layout manager to position the components inside the container OOP10 - M. Joldoş - T.U. Cluj 22

Tip: Code a GUI's Look and Actions Separately The task of designing a Swing GUI can be divided into two main subtasks: 1. Designing and coding the appearance of the GUI on the screen 2. Designing and coding the actions performed in response to user actions In particular, it is useful to implement the actionperformed() method as a stub, until the GUI looks the way it should public void actionperformed(actionevent e) {} This philosophy is at the heart of the technique used by the Model-View-Controller pattern OOP10 - M. Joldoş - T.U. Cluj 23

Using Inheritance to Customize Frames Use inheritance for complex frames to make programs easier to understand Design a subclass of JFrame Store the components as instance fields Initialize them in the constructor of your subclass If initialization code gets complex, simply add some helper methods OOP10 - M. Joldoş - T.U. Cluj 24

Layout Management Up to now, we have had limited control over layout of components When we used a panel, it arranged the components from the left to the right User-interface components are arranged by placing them inside containers Each container has a layout manager that directs the arrangement of its components Some useful layout managers: border layout flow layout grid layout box layout OOP10 - M. Joldoş - T.U. Cluj 25

Layout Management By default, JPanel places components from left to right and starts a new row when needed Panel layout carried out by FlowLayout layout manager Can set other layout managers panel.setlayout(new BorderLayout()); OOP10 - M. Joldoş - T.U. Cluj 26

Border Layout Border layout groups container into five areas: center, north, west, south and east Components expand to fill space in the border layout OOP10 - M. Joldoş - T.U. Cluj 27

Border Layout Default layout manager for a frame (technically, the frame's content pane) When adding a component, specify the position like this: panel.add(component, BorderLayout.NORTH); Expands each component to fill the entire allotted area If that is not desirable, place each component inside a panel OOP10 - M. Joldoş - T.U. Cluj 28

FlowLayout Layout Manager The FlowLayout layout manager arranges com-ponents in order from left to right and top to bottom across a container Constructors: public FlowLayout(); public FlowLayout(int align); public FlowLayout(int align, int horizontalgap, int verticalgap); The alignment can be LEFT, RIGHT, or CENTER Default layout manager for JPanel OOP10 - M. Joldoş - T.U. Cluj 29

Grid Layout Arranges components in a grid with a fixed number of rows and columns Resizes each component so that they all have same size Expands each component to fill the entire allotted area Add the components, row by row, left to right: JPanel numberpanel = new JPanel(); numberpanel.setlayout(new GridLayout(4, 3)); numberpanel.add(button7); numberpanel.add(button8); numberpanel.add(button9); numberpanel.add(button4);... OOP10 - M. Joldoş - T.U. Cluj 30

Examples: FlowLayout and Grid Layout BlueJ: TestGridLayout BlueJ: TestFlowLayout OOP10 - M. Joldoş - T.U. Cluj 31

Grid Bag Layout Tabular arrangement of components Columns can have different sizes Components can span multiple columns Quite complex to use Fortunately, you can create acceptable-looking layouts by nesting panels Give each panel an appropriate layout manager Panels don t have visible borders Use as many panels as needed to organize components OOP10 - M. Joldoş - T.U. Cluj 32

BoxLayout Layout Manager The BoxLayout layout manager arranges components within a container in a single row or a single column. The spacing and alignment of each element on each row or column can be individually controlled. Containers using BoxLayout managers can be nested inside each other to produce complex layouts Constructor: public BoxLayout(Container c, int direction); The direction can be X_AXIS or Y_AXIS Rigid areas and glue regions can be used to space out components within a BoxLayout OOP10 - M. Joldoş - T.U. Cluj 33

Example: Creating a BoxLayout JFrame jf = new JFrame("TestBoxLayout"); jf.setdefaultcloseoperation(jframe.exit_on_close); jf.setsize(new Dimension( 200, 200)); jf.setlocation(300, 300); // Create a new panel JPanel p = new JPanel(); // Set the layout manager p.setlayout(new BoxLayout(p, BoxLayout.Y_AXIS)); // Add buttons // leave some vertical space before button p.add( Box.createRigidArea(new Dimension(0,5)) ); addabutton( "Button 1", p ); // vertical space between buttons p.add( Box.createRigidArea(new Dimension(0,20)) ); addabutton( "Button 2", p ); p.add( Box.createRigidArea(new Dimension(0,5)) ); addabutton( "Button 3", p ); p.setbackground(color.cyan); // Add the new panel to the existing container jf. add( p ); jf.setvisible(true); private static void addabutton( String text, Container container) { JButton button = new JButton(text); button.setalignmentx( Component.CENTER_ALIGNMENT); container.add(button); } OOP10 - M. Joldoş - T.U. Cluj 34

Choices Radio buttons Check boxes Combo boxes OOP10 - M. Joldoş - T.U. Cluj 35

Radio Buttons For a small set of mutually exclusive choices, use radio buttons or a combo box In a radio button set, only one button can be selected at a time When a button is selected, previously selected button in set is automatically turned off OOP10 - M. Joldoş - T.U. Cluj 36

Radio Buttons Button group does not place buttons close to each other on container It is your job to arrange buttons on screen isselected(): called to find out if a button is currently selected or not if(largebutton.isselected()) size = LARGE_SIZE; Call setselected(true) on a radio button in group before making the enclosing frame visible OOP10 - M. Joldoş - T.U. Cluj 37

Borders Place a border around a panel to group its contents visually EtchedBorder: three-dimensional etched effect Can add a border to any component, but most commonly to panels: Jpanel panel = new JPanel (); panel.setborder(new EtchedBorder ()); TitledBorder: a border with a title: Panel.setBorder(new TitledBorder(new EtchedBorder(), "Size")); OOP10 - M. Joldoş - T.U. Cluj 38

Check Boxes Two states: checked and unchecked Use one checkbox for a binary choice Use a group of check boxes when one selection does not exclude another Example: "bold" and "italic" when choosing a font style Construct by giving the name in the constructor: JCheckBox italiccheckbox = new JCheckBox("Italic"); Don't place into a button group OOP10 - M. Joldoş - T.U. Cluj 39

Combo Boxes For a large set of choices, use a combo box Uses less space than radio buttons "Combo": combination of a list and a text field The text field displays the name of the current selection OOP10 - M. Joldoş - T.U. Cluj 40

Combo Boxes If combo box is editable, user can type own selection Use seteditable() method Add strings with additem() method: JComboBox facenamecombo = new JComboBox(); facenamecombo.additem("serif"); facenamecombo.additem("sansserif");... Get user selection with getselecteditem() (return type is Object) String selectedstring = (String) facenamecombo.getselecteditem(); Select an item with setselecteditem() OOP10 - M. Joldoş - T.U. Cluj 41

Radio Buttons, Check Boxes, and Combo Boxes They generate an ActionEvent whenever the user selects an item An example: ChoiceFrame All components notify the same listener object When user clicks on any component, we ask each component for its current content Then redraw text sample with the new font BlueJ: ChoiceFrameViewer JLabel in CENTER position JPanel with GridLayout in SOUTH position OOP10 - M. Joldoş - T.U. Cluj 42

Layout Management Step 1: Make a sketch of your desired component layout Step 2: Find groupings of adjacent components with the same layout Step 3: Identify layouts for each group Step 4: Group the groups together Step 5: Write the code to generate the layout OOP10 - M. Joldoş - T.U. Cluj 43

Combining Layout Managers to Produce a Result To create just the look you want, it is sometimes useful to create multiple containers inside each other, each with its own layout manager For example, a top-level panel might use a horizontal box layout, and that panel may contain two or more panels using vertical box layouts The result is complete control of component spacing in both dimensions OOP10 - M. Joldoş - T.U. Cluj 44

// Create a new high-level panel JPanel phoriz = new JPanel(); phoriz.setlayout(new BoxLayout(pHoriz, BoxLayout.X_AXIS)); add( phoriz ); // Create two subordinate panels JPanel pvertl = new JPanel(); JPanel pvertr = new JPanel(); pvertl.setlayout(new BoxLayout(pVertL, BoxLayout.Y_AXIS)); pvertr.setlayout(new BoxLayout(pVertR, BoxLayout.Y_AXIS)); // Add to phoriz with a horizontal space between panels phoriz.add( pvertl ); phoriz.add( Box.createRigidArea(new Dimension(20,0)) ); phoriz.add( pvertr ); // Create degrees Celsius field l1 = new JLabel("deg C:", JLabel.RIGHT); pvertl.add( l1 ); t1 = new JTextField("0.0",15); t1.addactionlistener( chnd ); pvertr.add( t1 ); // Create degrees Fahrenheight field l2 = new JLabel("deg F:", JLabel.RIGHT); pvertl.add( l2 ); t2 = new JTextField("32.0",15); t2.addactionlistener( fhnd ); pvertr.add( t2 ); Example: Nested Containers and Layouts p H o r i z p V e r t L l 1 l 2 Structure: p V e r t R Result: OOP10 - M. Joldoş - T.U. Cluj 45 t 1 t 2

Borders (Swing) OOP10 - M. Joldoş - T.U. Cluj 46

Menus A frame contains a menu bar The menu bar contains menus A menu contains submenus and menu items Pull-Down Menus Menu bar Menu Menu item OOP10 - M. Joldoş - T.U. Cluj 47

Menus (Swing) JMenu Accelerator Mnemonic JMenuBar JMenuItem JRadioButtonMenuItem JSeparator JCheckBoxMenuItem JPopupMenu OOP10 - M. Joldoş - T.U. Cluj 48

Menu Items Add menu items and submenus with the add() method: JMenuItem fileexititem = new JMenuItem("Exit"); filemenu.add(fileexititem); A menu item has no further submenus Menu items generate action events Add a listener to each menu item: fileexititem.addactionlistener(listener); Add action listeners only to menu items, not to menus or the menu bar OOP10 - M. Joldoş - T.U. Cluj 49

A Sample Program Builds up a small but typical menu Traps action events from menu items To keep program readable, use a separate method for each menu or set of related menus createfaceitem(): creates menu item to change the font face createsizeitem() createstyleitem() BlueJ MenuFrameViewer OOP10 - M. Joldoş - T.U. Cluj 50

Text Areas Use a JTextArea to show multiple lines of text You can specify the number of rows and columns: final int ROWS = 10; final int COLUMNS = 30; JTextArea textarea = new JTextArea(ROWS, COLUMNS); The number of characters per line for a JTextField or JTextArea object is the number of em spaces An em space is the space needed to hold one uppercase letter M (widest in the alphabet) A line specified to hold 20 M 's will almost always be able to hold more than 20 characters OOP10 - M. Joldoş - T.U. Cluj 51

Text Areas settext(): to set the text of a text field or text area append(): to add text to the end of a text area Use newline characters to separate lines: textarea.append(account.getbalance() + "\n"); To use for display purposes only: textarea.seteditable(false); // program can call settext and append to change it To add scroll bars to a text area: JTextArea textarea = new JTextArea(ROWS, COLUMNS); JScrollPane scrollpane = new JScrollPane(textArea); OOP10 - M. Joldoş - T.U. Cluj 52

Text Areas BlueJ TextAreaViewer OOP10 - M. Joldoş - T.U. Cluj 53

Exploring the Swing Documentation For more sophisticated effects, explore the Swing documentation The documentation can be quite intimidating at first glance Next example will show how to use the documentation to your advantage OOP10 - M. Joldoş - T.U. Cluj 54

Example: A Color Mixer It should be fun to mix your own colors, with a slider for the red, green, and blue values There are over 50 methods in JSlider class and over 250 inherited methods Some method descriptions look scary OOP10 - M. Joldoş - T.U. Cluj 55

How do I construct a JSlider? Look at the Java version 5.0 API documentation There are six constructors for the JSlider class Learn about one or two of them Strike a balance somewhere between the trivial and the bizarre Too limited: public JSlider() Creates a horizontal slider with the range 0 to 100 and an initial value of 50 public JSlider(BoundedRangeModel brm) Creates a horizontal slider using the specified BoundedRangeModel Bizarre: public JSlider(int min, int max, int value) Creates a horizontal slider using the specified min, max, and value. Useful: OOP10 - M. Joldoş - T.U. Cluj 56

How Can I Get Notified When the User Has Moved a JSlider? There is no addactionlistener method There is a method public void addchangelistener(changelistener l) Click on the ChangeListener link to learn more It has a single method: void statechanged(changeevent e) OOP10 - M. Joldoş - T.U. Cluj 57

How Can I Get Notified When the User Has Moved a JSlider? Apparently, method is called whenever user moves the slider What is a ChangeEvent? It inherits getsource() method from superclass EventObject getsource(): tells us which component generated this event OOP10 - M. Joldoş - T.U. Cluj 58

How Can I Tell to Which Value the User Has Set a JSlider? Now we have a plan: Add a change event listener to each slider When slider is changed, statechanged() method is called Find out the new value of the slider Re-compute color value Repaint color panel Need to get the current value of the slider Look at all the methods that start with get; you find: public int getvalue() Returns the slider's value. OOP10 - M. Joldoş - T.U. Cluj 59

The Components of the SliderFrame JPanel in CENTER position JPanel with GridLayout in SOUTH position OOP10 - M. Joldoş - T.U. Cluj 60

Icons JLabels, JButtons, and JMenuItems can have icons An icon is just a small picture (usually) It is not required to be small An icon is an object of the ImageIcon class It is based on a digital picture file such as.gif,.jpg, or.tiff Labels, buttons, and menu items may display a string, an icon, a string and an icon, or nothing OOP10 - M. Joldoş - T.U. Cluj 61

Icons The class ImageIcon is used to convert a picture file to a Swing icon ImageIcon dukeicon = new ImageIcon("duke_waving.gif"); The picture file must be in the same directory as the class in which this code appears, unless a complete or relative path name is given Note that the name of the picture file is given as a string An icon can be added to a label using the seticon method as follows: JLabel dukelabel = new JLabel("Mood check"); dukelabel.seticon(dukeicon); OOP10 - M. Joldoş - T.U. Cluj 62

Icons Instead, an icon can be given as an argument to the JLabel constructor: JLabel dukelabel = new JLabel(dukeIcon); Text can be added to the label as well using the settext method: dukelabel.settext("mood check"); Icons and text may be added to JButtons and JMenuItems in the same way as they are added to a JLabel JButton happybutton = new JButton("Happy"); ImageIcon happyicon = new ImageIcon("smiley.gif"); happybutton.seticon(happyicon); OOP10 - M. Joldoş - T.U. Cluj 63

Icons Button or menu items can be created with just an icon by giving the ImageIcon object as an argument to the JButton or JMenuItem constructor ImageIcon happyicon = new ImageIcon("smiley.gif"); JButton smilebutton = new JButton(happyIcon); JMenuItem happychoice = new JMenuItem(happyIcon); A button or menu item created without text should use the setactioncommand() method to explicitly set the action command, since there is no string OOP10 - M. Joldoş - T.U. Cluj 64

Summary GUI Containers and Components MVC and Swing Layout management Radio buttons Check boxes Combo boxes Grouping buttons Menus Text areas Exploring documentation: using JSlider Icons setting icons and text OOP10 - M. Joldoş - T.U. Cluj 65