Introduction to Graphics

Slides:



Advertisements
Similar presentations
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Advertisements

Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
1 Chapter 7 Graphics and Event Handling. 2 Overview The java.awt and javax.swing packages and their subpackages support graphics and event handling. Many.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
GUI Basics: Introduction. Creating GUI Objects // Create a button with text OK JButton jbtOK = new JButton("OK"); // Create a label with text "Enter your.
Java Programming Chapter 10 Graphical User Interfaces.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
GUI programming Graphical user interface-based programming.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Graphics and Java 2D. 2 Introduction Java’s graphics capabilities –Drawing 2D shapes –Controlling colors –Controlling fonts Java 2D API –More sophisticated.
GUI Chapter 10 Graphics context and objects Creating a window based application JFrame, JTextField, JButton Containers and Controls Graphics commands Layout.
1 Review Polymorphism –“having many forms” –Helps build extensible systems Dynamic/late binding –Implements polymorphic processing of objects –Use superclass.
CSTP FS99CS423 (cotter)1 Java Graphics java.awt.*;
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Javax.swing Class JOptionPane Java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JOptionPane.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
GUI Basics. Agenda What GUI How to make in java Creating frames Frequently used GUI components Layout Managers.
Basics of GUI Programming Chapter 11 and Chapter 22.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 27.1 Test-Driving the Drawing Shapes Application.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
1 Chapter 13 – More GUI Components Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides users with basic.
1 Lecture 8: User Interface Components with Swing.
Jozef Goetz Credits: Copyright  Pearson Education, Inc. All rights reserved. expanded by J. Goetz, 2016.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Lecture 6 Object Oriented Programming Using Java By Rashid Ahmad Department of Computer Science University of Peshawar.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
GUI Programming using Java - Event Handling
GUIs and Events Rick Mercer.
CSC 205 Programming II Lecture 5 AWT - I.
Welcome To java
Chapter 14 – Exception Handling
Appendix I GUI Components and Event Handling
A First Look at GUI Applications
Lecture 09 Applets.
Java Programming: From Problem Analysis to Program Design,
Ellen Walker Hiram College
Chapter 13: Advanced GUIs and Graphics
MSIS670: Object-Oriented Software Engineering
Graphical user interface-based programming
IFS410: Advanced Analysis and Design
Introduction to Event Handling
COP 4610L: Applications in the Enterprise Spring 2005
Chapter 7 (Book Chapter 14)
Advanced Programming in Java
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Introduction to Graphics An appealing feature of Java Made easy by many standard library calls that are not included in many languages With graphics one can easily draw shapes, one can control colors and fonts, one can organize the screen in a user-friendly way.

An JOptionPane example Graphics An JOptionPane example import javax.swing.JOptionPane; public class DialogDemo { public static void main(String[] args) { String ans; ans = JOptionPane.showInputDialog(null, "Speed in miles per hour?"); double mph = Double.parseDouble(ans); double kph = 1.621 * mph; JOptionPane.showMessageDialog(null, "KPH = " + kph); System.exit(0); }

Frame Windows import javax.swing.*; public class EmptyFrameViewer{ public static void main(String[] args) { JFrame frame = new JFrame(); final int FRAME_WIDTH = 300; final int FRAME_HEIGHT = 400; frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setTitle("An Empty Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }

Part of the java class hierarchy structure awt and swing Most of the GUI classes are provided in Java by the Abstract Windowing Tools (AWT) package (java.awt). AWT was expanded with the Swing classes (javax.swing) in Java 2 platform Swing classes provide alternative components that have more functionality than AWT We shall prefer using swing Part of the java class hierarchy structure Classes of AWT such Color, Font, Graphics, Component are derived from the Object superclass.

Java’s Coordinate System Scheme for identifying all points on screen Upper-left corner has coordinates (0,0) Coordinate point composed of x-coordinate and y-coordinate

Java coordinate system. Units are measured in pixels.

Graphics Context and Graphics Objects Enables drawing on screen Graphics object manages graphics context Controls how information is drawn Class Graphics is abstract Cannot be instantiated Contributes to Java’s portability Class Component method paint takes Graphics object public void paint( Graphics g ) Called through method repaint

Color Control Class Color Defines methods and constants for manipulating colors Colors are created from red, green and blue components RGB values

Color class static constants and RGB values.

Color methods and color-related Graphics methods.

The Component Class A superclass for many classes in AWT Its method paint() takes a Graphics object as an argument: public void paint (Graphics g) Derived classes from Component will override paint() to perform various graphics operations with the help of the g Graphics object passed as a parameter.

import java.awt.*; import java.awt.event.*; // Java extension packages import javax.swing.*; public class ShowColors extends JFrame { // constructor sets window's title bar string and dimensions public ShowColors() { super( "Using colors" ); // this will put a title on the frame bar setSize( 400, 130 ); // size in pixels show(); } // draw rectangles and Strings in different colors public void paint( Graphics g ) { // call superclass's paint method super.paint( g ); // setColor, fillRect, drawstring, getColor, getRed etc // are methods of Graphics // set new drawing color using integers for R/G/B g.setColor( new Color( 255, 0, 0 ) ); g.fillRect( 25, 25, 100, 20 ); g.drawString( "Current RGB: " + g.getColor(), 130, 40 ); // set new drawing color using floats g.setColor( new Color( 0.0f, 1.0f, 0.0f ) ); g.fillRect( 25, 50, 100, 20 ); g.drawString( "Current RGB: " + g.getColor(), 130, 65 );

// set new drawing color using static Color objects g.setColor( Color.blue ); g.fillRect( 25, 75, 100, 20 ); g.drawString( "Current RGB: " + g.getColor(), 130, 90 ); // display individual RGB values Color color = Color.magenta; g.setColor( color ); g.fillRect( 25, 100, 100, 20 ); g.drawString( "RGB values: " + color.getRed() + ", " + color.getGreen() + ", " + color.getBlue(), 130, 115 ); } // execute application public static void main( String args[] ) { ShowColors application = new ShowColors(); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); } // end class ShowColors

Another class in Swing that inherits from Component Applets Another class in Swing that inherits from Component Can be executed by any web browser that supports Java, or Java AppletViewer Not a stand-alone application (cf. JFrame)

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ShowColors extends JApplet { public void paint( Graphics g ) { // call superclass's paint method super.paint( g ); // set new drawing color using integers g.setColor( new Color( 255, 0, 0 ) ); g.fillRect( 25, 25, 100, 20 ); g.drawString( "Current RGB: " + g.getColor(), 130, 40 ); // set new drawing color using floats g.setColor( new Color( 0.0f, 1.0f, 0.0f ) ); g.fillRect( 25, 50, 100, 20 ); g.drawString( "Current RGB: " + g.getColor(), 130, 65 ); // set new drawing color using static Color objects g.setColor( Color.blue ); g.fillRect( 25, 75, 100, 20 ); g.drawString( "Current RGB: " + g.getColor(), 130, 90 ); // display individual RGB values Color color = Color.magenta; g.setColor( color ); g.fillRect( 25, 100, 100, 20 ); g.drawString( "RGB values: " + color.getRed() + ", " + color.getGreen() + ", " + color.getBlue(), 130, 115 ); } } // end class ShowColors

Applets Another important difference between applets and frames is that the sizing and creation of the window is done in HTML instead of Java. What was done through the constructor of the JFrame object is done for applets through the HTML code: We shall simplify our work with applets in this course by requiring that you always use the JDK appletviewer appletviewer ShowColors.html // this is the file ShowColors.html <html> <applet code = "ShowColors.class" width = "400" height = "130"> </applet> </html>

GUI Components A visual index to the swing components

Some Basic GUI Components

Swing Overview Swing GUI components Package javax.swing Components originate from AWT (package java.awt) Contain look and feel Appearance and how users interact with program

Swing Overview (cont.) Class Component Class Container Contains method paint for drawing Component onscreen Class Container Collection of related components Contains method add for adding components Class JComponent Pluggable look and feel for customizing look and feel Shortcut keys (mnemonics) Common event-handling capabilities

Common superclasses of many of the Swing components.

JLabel Label Provide text on GUI Defined with class JLabel Can display: Single line of read-only text Image Text and image

Building of GUI is done in the constructor 1 // LabelTest.java 2 // Demonstrating the JLabel class. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class LabelTest extends JFrame { 12 private JLabel label1, label2, label3; 13 14 // set up GUI 15 public LabelTest() 16 { 17 super( "Testing JLabel" ); 18 19 // get content pane and set its layout 20 Container container = getContentPane(); 21 container.setLayout( new FlowLayout() ); 22 23 // JLabel constructor with a string argument 24 label1 = new JLabel( "Label with text" ); 25 label1.setToolTipText( "This is label1" ); 26 container.add( label1 ); 27 28 // JLabel constructor with string, Icon and 29 // alignment arguments 30 Icon bug = new ImageIcon( "bug1.gif" ); 31 label2 = new JLabel( "Label with text and icon", 32 bug, SwingConstants.LEFT ); 33 label2.setToolTipText( "This is label2" ); 34 container.add( label2 ); 35 Declare three JLabels Building of GUI is done in the constructor Create first JLabel with text “Label with text” Tool tip is text that appears when user moves cursor over JLabel Create second JLabel with text to left of image

Create third JLabel with text below image 36 // JLabel constructor no arguments 37 label3 = new JLabel(); 38 label3.setText( "Label with icon and text at bottom" ); 39 label3.setIcon( bug ); 40 label3.setHorizontalTextPosition( SwingConstants.CENTER ); 41 label3.setVerticalTextPosition( SwingConstants.BOTTOM ); 42 label3.setToolTipText( "This is label3" ); 43 container.add( label3 ); 44 45 setSize( 275, 170 ); 46 setVisible( true ); 47 } 48 49 // execute application 50 public static void main( String args[] ) 51 { 52 LabelTest application = new LabelTest(); 53 54 application.setDefaultCloseOperation( 55 JFrame.EXIT_ON_CLOSE ); 56 } 57 58 } // end class LabelTest Create third JLabel with text below image

Event-Handling Model GUIs are event driven Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc. Class java.awt.AWTEvent

Some event classes of package java.awt.event

Event-Handling Model (cont.) Three parts Event source GUI component with which user interacts Event object Encapsulates information about event that occurred Event listener Receives event object when notified, then responds Programmer must perform two tasks Register event listener for event source Implement event-handling method (event handler)

Event-listener interfaces of package java.awt.event

JTextField and JPasswordField Single-line area in which user can enter text JPasswordField Extends JTextField Hides characters that user enters

Declare three JTextFields and one JPasswordField 1 // TextFieldTest.java 2 // Demonstrating the JTextField class. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class TextFieldTest extends JFrame { 12 private JTextField textField1, textField2, textField3; 13 private JPasswordField passwordField; 14 15 // set up GUI 16 public TextFieldTest() 17 { 18 super( "Testing JTextField and JPasswordField" ); 19 20 Container container = getContentPane(); 21 container.setLayout( new FlowLayout() ); 22 23 // construct textfield with default sizing 24 textField1 = new JTextField( 10 ); 25 container.add( textField1 ); 26 27 // construct textfield with default text 28 textField2 = new JTextField( "Enter text here" ); 29 container.add( textField2 ); 30 31 // construct textfield with default text and 32 // 20 visible elements and no event handler 33 textField3 = new JTextField( "Uneditable text field", 20 ); 34 textField3.setEditable( false ); 35 container.add( textField3 ); Declare three JTextFields and one JPasswordField First JTextField contains empty string Second JTextField contains text “Enter text here” Third JTextField contains uneditable text

Every TextFieldHandler instance is an ActionListener 36 37 // construct textfield with default text 38 passwordField = new JPasswordField( "Hidden text" ); 39 container.add( passwordField ); 40 41 // register event handlers 42 TextFieldHandler handler = new TextFieldHandler(); 43 textField1.addActionListener( handler ); 44 textField2.addActionListener( handler ); 45 textField3.addActionListener( handler ); 46 passwordField.addActionListener( handler ); 47 48 setSize( 325, 100 ); 49 setVisible( true ); 50 } 51 52 // execute application 53 public static void main( String args[] ) 54 { 55 TextFieldTest application = new TextFieldTest(); 56 57 application.setDefaultCloseOperation( 58 JFrame.EXIT_ON_CLOSE ); 59 } 60 61 // private inner class for event handling 62 private class TextFieldHandler implements ActionListener { 63 64 // process text field events 65 public void actionPerformed( ActionEvent event ) 66 { 67 String string = ""; 68 69 // user pressed Enter in JTextField textField1 70 if ( event.getSource() == textField1 ) JPasswordField contains text “Hidden text,” but text appears as series of asterisks (*) Register GUI components with TextFieldHandler (register for ActionEvents) Every TextFieldHandler instance is an ActionListener Method actionPerformed invoked when user presses Enter in GUI field

71 string = "textField1: " + event 71 string = "textField1: " + event.getActionCommand(); 72 73 // user pressed Enter in JTextField textField2 74 else if ( event.getSource() == textField2 ) 75 string = "textField2: " + event.getActionCommand(); 76 77 // user pressed Enter in JTextField textField3 78 else if ( event.getSource() == textField3 ) 79 string = "textField3: " + event.getActionCommand(); 80 81 // user pressed Enter in JTextField passwordField 82 else if ( event.getSource() == passwordField ) { 83 JPasswordField pwd = 84 ( JPasswordField ) event.getSource(); 85 string = "passwordField: " + 86 new String( passwordField.getPassword() ); 87 } 88 89 JOptionPane.showMessageDialog( null, string ); 90 } 91 92 } // end private inner class TextFieldHandler 93 94 } // end class TextFieldTest

TextFieldTest.java

How Event Handling Works Two open questions How did event handler get registered? Answer: Through component’s method addActionListener Lines 43-46 of TextFieldTest.java How does component know to call actionPerformed? Event is dispatched only to listeners of appropriate type Each event type has corresponding event-listener interface Event ID specifies event type that occurred

Event registration for JTextField textField1.

JButton Button Component user clicks to trigger a specific action Several different types Command buttons Check boxes Toggle buttons Radio buttons javax.swing.AbstractButton subclasses Command buttons are created with class JButton Generate ActionEvents when user clicks button

The Button Hierarchy

Create two references to JButton instances 1 // ButtonTest.java 2 // Creating JButtons. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class ButtonTest extends JFrame { 12 private JButton plainButton, fancyButton; 13 14 // set up GUI 15 public ButtonTest() 16 { 17 super( "Testing Buttons" ); 18 19 // get content pane and set its layout 20 Container container = getContentPane(); 21 container.setLayout( new FlowLayout() ); 22 23 // create buttons 24 plainButton = new JButton( "Plain Button" ); 25 container.add( plainButton ); 26 27 Icon bug1 = new ImageIcon( "bug1.gif" ); 28 Icon bug2 = new ImageIcon( "bug2.gif" ); 29 fancyButton = new JButton( "Fancy Button", bug1 ); 30 fancyButton.setRolloverIcon( bug2 ); 31 container.add( fancyButton ); 32 33 // create an instance of inner class ButtonHandler 34 // to use for button event handling 35 ButtonHandler handler = new ButtonHandler(); Create two references to JButton instances Instantiate JButton with text Instantiate JButton with image and rollover image Instantiate ButtonHandler for JButton event handling

Register JButtons to receive events from ButtonHandler 36 fancyButton.addActionListener( handler ); 37 plainButton.addActionListener( handler ); 38 39 setSize( 275, 100 ); 40 setVisible( true ); 41 } 42 43 // execute application 44 public static void main( String args[] ) 45 { 46 ButtonTest application = new ButtonTest(); 47 48 application.setDefaultCloseOperation( 49 JFrame.EXIT_ON_CLOSE ); 50 } 51 52 // inner class for button event handling 53 private class ButtonHandler implements ActionListener { 54 55 // handle button event 56 public void actionPerformed( ActionEvent event ) 57 { 58 JOptionPane.showMessageDialog( null, 59 "You pressed: " + event.getActionCommand() ); 60 } 61 62 } // end private inner class ButtonHandler 63 64 } // end class ButtonTest When user clicks JButton, ButtonHandler invokes method actionPerformed of all registered listeners

ButtonTest.java