Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Graphics

Similar presentations


Presentation on theme: "Introduction to Graphics"— Presentation transcript:

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

2 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 = * mph; JOptionPane.showMessageDialog(null, "KPH = " + kph); System.exit(0); }

3 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); }

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

5 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

6 Java coordinate system. Units are measured in pixels.

7 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

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

9 Color class static constants and RGB values.

10 Color methods and color-related Graphics methods.

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

12 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 );

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

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

15 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

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

17 GUI Components A visual index to the swing components

18 Some Basic GUI Components

19 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

20 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

21 Common superclasses of many of the Swing components.

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

23 Building of GUI is done in the constructor
1 // LabelTest.java 2 // Demonstrating the JLabel class // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; // Java extension packages 9 import javax.swing.*; public class LabelTest extends JFrame { private JLabel label1, label2, label3; // set up GUI public LabelTest() { super( "Testing JLabel" ); // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() ); // JLabel constructor with a string argument label1 = new JLabel( "Label with text" ); label1.setToolTipText( "This is label1" ); container.add( label1 ); // JLabel constructor with string, Icon and // alignment arguments Icon bug = new ImageIcon( "bug1.gif" ); label2 = new JLabel( "Label with text and icon", bug, SwingConstants.LEFT ); label2.setToolTipText( "This is label2" ); 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

24 Create third JLabel with text below image
// JLabel constructor no arguments label3 = new JLabel(); label3.setText( "Label with icon and text at bottom" ); label3.setIcon( bug ); label3.setHorizontalTextPosition( SwingConstants.CENTER ); label3.setVerticalTextPosition( SwingConstants.BOTTOM ); label3.setToolTipText( "This is label3" ); container.add( label3 ); setSize( 275, 170 ); setVisible( true ); } // execute application public static void main( String args[] ) { LabelTest application = new LabelTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class LabelTest Create third JLabel with text below image

25 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

26 Some event classes of package java.awt.event

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

28 Event-listener interfaces of package java.awt.event

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

30 Declare three JTextFields and one JPasswordField
1 // TextFieldTest.java 2 // Demonstrating the JTextField class // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; // Java extension packages 9 import javax.swing.*; public class TextFieldTest extends JFrame { private JTextField textField1, textField2, textField3; private JPasswordField passwordField; // set up GUI public TextFieldTest() { super( "Testing JTextField and JPasswordField" ); Container container = getContentPane(); container.setLayout( new FlowLayout() ); // construct textfield with default sizing textField1 = new JTextField( 10 ); container.add( textField1 ); // construct textfield with default text textField2 = new JTextField( "Enter text here" ); container.add( textField2 ); // construct textfield with default text and // 20 visible elements and no event handler textField3 = new JTextField( "Uneditable text field", 20 ); textField3.setEditable( false ); 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

31 Every TextFieldHandler instance is an ActionListener
// construct textfield with default text passwordField = new JPasswordField( "Hidden text" ); container.add( passwordField ); // register event handlers TextFieldHandler handler = new TextFieldHandler(); textField1.addActionListener( handler ); textField2.addActionListener( handler ); textField3.addActionListener( handler ); passwordField.addActionListener( handler ); setSize( 325, 100 ); setVisible( true ); } // execute application public static void main( String args[] ) { TextFieldTest application = new TextFieldTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // private inner class for event handling private class TextFieldHandler implements ActionListener { // process text field events public void actionPerformed( ActionEvent event ) { String string = ""; // user pressed Enter in JTextField textField 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

32 71 string = "textField1: " + event
string = "textField1: " + event.getActionCommand(); // user pressed Enter in JTextField textField else if ( event.getSource() == textField2 ) string = "textField2: " + event.getActionCommand(); // user pressed Enter in JTextField textField else if ( event.getSource() == textField3 ) string = "textField3: " + event.getActionCommand(); // user pressed Enter in JTextField passwordField else if ( event.getSource() == passwordField ) { JPasswordField pwd = ( JPasswordField ) event.getSource(); string = "passwordField: " new String( passwordField.getPassword() ); } JOptionPane.showMessageDialog( null, string ); } } // end private inner class TextFieldHandler } // end class TextFieldTest

33 TextFieldTest.java

34 How Event Handling Works
Two open questions How did event handler get registered? Answer: Through component’s method addActionListener Lines 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

35 Event registration for JTextField textField1.

36 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

37 The Button Hierarchy

38 Create two references to JButton instances
1 // ButtonTest.java // Creating JButtons // Java core packages import java.awt.*; import java.awt.event.*; // Java extension packages import javax.swing.*; public class ButtonTest extends JFrame { private JButton plainButton, fancyButton; // set up GUI public ButtonTest() { super( "Testing Buttons" ); // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() ); // create buttons plainButton = new JButton( "Plain Button" ); container.add( plainButton ); Icon bug1 = new ImageIcon( "bug1.gif" ); Icon bug2 = new ImageIcon( "bug2.gif" ); fancyButton = new JButton( "Fancy Button", bug1 ); fancyButton.setRolloverIcon( bug2 ); container.add( fancyButton ); // create an instance of inner class ButtonHandler // to use for button event handling 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

39 Register JButtons to receive events from ButtonHandler
fancyButton.addActionListener( handler ); plainButton.addActionListener( handler ); setSize( 275, 100 ); setVisible( true ); } // execute application public static void main( String args[] ) { ButtonTest application = new ButtonTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // inner class for button event handling private class ButtonHandler implements ActionListener { // handle button event public void actionPerformed( ActionEvent event ) { JOptionPane.showMessageDialog( null, "You pressed: " + event.getActionCommand() ); } } // end private inner class ButtonHandler } // end class ButtonTest When user clicks JButton, ButtonHandler invokes method actionPerformed of all registered listeners

40 ButtonTest.java


Download ppt "Introduction to Graphics"

Similar presentations


Ads by Google