Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Review Polymorphism –“having many forms” –Helps build extensible systems Dynamic/late binding –Implements polymorphic processing of objects –Use superclass.

Similar presentations


Presentation on theme: "1 Review Polymorphism –“having many forms” –Helps build extensible systems Dynamic/late binding –Implements polymorphic processing of objects –Use superclass."— Presentation transcript:

1 1 Review Polymorphism –“having many forms” –Helps build extensible systems Dynamic/late binding –Implements polymorphic processing of objects –Use superclass reference to refer to subclass object –Program chooses “correct” method in subclass at execution Abstract Class Interface

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

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

4 4 Creating a window Top-level containers –Window Jdialog Jframe –Panel Japplet User-interface components are arranged by placing them in a Swing Container object –E.g. Jbutton, Jlabel, Jlist

5 5 Dialog by JOptionPane Several Swing component classes can directly instantiate and display dialogs. E.g. JoptionPane import javax.swing.*; class MessageDialog { public static void main(String[] args) { JOptionPane.showMessageDialog(null,"Hi, how are you?"); JOptionPane.showMessageDialog(null, "Show second dialog message."); }

6 6 Dialog by JOptionPane Another 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); }

7 7 Frame Windows: An Example 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 = 300; frame.setBounds(100, 100, FRAME_WIDTH, FRAME_HEIGHT); frame.setTitle("An Empty Frame"); //Makes the frame perform the given action when it closes. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //make a frame appear on the screen after creating it (default is invisible) frame.setVisible(true); }

8 8 Jframe: Commonly used constructors and methods public JFrame()or public JFrame(String title) –Creates a frame with an optional title. setBounds(int x,int y,int width,int height) setSize(int width,int height) setBackground(Color c) setVisible(boolean b) : pack() –Resizes the frame to fit the components inside it setTitle(String name) getTitle() setResiable(boolean m)

9 9 Applets Review Can be executed by any web browser that supports Java, or Java AppletViewer –Not a stand-alone application (cf. JFrame) –sizing and creation of the window is done in HTML instead of Java –In this course, always use the JDK appletviewer appletviewer ShowColors.html // this is the file EmptyAppletViewer.html

10 10 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class EmptyAppletViewer extends JApplet { public void paint( Graphics g ) { // call superclass's paint method super.paint( g ); // add further implementations here } Applets : A basic Example

11 11 Java ’ s Coordinate System Review 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.

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

13 13 The class hierarchy https://www3.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI_2.html

14 14 Swing Overview (cont.) Class Component –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

15 15 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. public abstract class Component extends Object implements ImageObserver, MenuContainer, Serializable

16 16 Graphics Context and Graphics Objects Graphics context –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

17 17 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 Orange, pink, cyan, magenta, yellow, black, white, gray, lightGray, darkGray, red, green, blue –Color methods and color-related Graphics methods. public Color( float r, float g, float b ) public int getRed() // Color class public int getGreen() // Color class public int getBlue() public Color getColor() public void setColor( Color c )

18 18 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 ); Graphics and Color Example: A Jframe Application

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

20 20 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 Graphics and Color Example: A Japplet Application

21 21 The class hierarchy of Swing's JComponents https://www3.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI_2.html

22 22 Graphic User Interface (GUI) Components A Visual Guide to Swing Components

23 23 Most of the Swing Components supports these features Text and icon. Keyboard short-cut Tool tips: display when the mouse-pointer pauses on the component. Look and feel: customized appearance and user interaction for the operating platform. Localization: different languages for different locale.

24 24 Some Basic GUI Components

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

26 26 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 JLabel sCreate first JLabel with text “ Label with text ” Create second JLabel with text to left of image Tool tip is text that appears when user moves cursor over JLabel Building of GUI is done in the constructor

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

28 28 Using images in GUI: ImageIcon javax.swing.ImageIcon class models an image icon. The ImageIcon class implements javax.swing.Icon interface, and hence, often upcasted and referenced as Icon. An ImageIcon is a fixed-size picture, typically small, and mainly used for decorating GUI components. To construct an ImageIcon, provide the image filename or URL. Image file type of GIF, PNG, JPG and BMP are supported.

29 29 Layout Management –Each container has a layout manager that directs the arrangement of its components –Components are added to a container which uses a layout manager to place them –Three useful layout managers are: 1) Border layout 2) Flow layout 3) Grid layout Page 29

30 30 Jframe ’s Content Pane A JFrame has a content pane which is a Container where you can add components –Use the getContentPane method to get its reference Container container= getContentPane(); –Set laylout container.setLayout( new FlowLayout() ); –Add components to the content pane container.add( label1 ); Page 30

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

32 32 Some event classes of package java.awt.event

33 33 Event-Handling Model (cont.) Event-handling model –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)

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

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

36 36 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 JTextField s and one JPasswordField First JTextField contains empty string Second JTextField contains text “ Enter text here ” Third JTextField contains uneditable text

37 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 ( * ) Every TextFieldHandler instance is an ActionListener Register GUI components with TextFieldHandler (register for ActionEvent s) Method actionPerformed invoked when user presses Enter in GUI field

38 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

39 39 TextFieldTest.java

40 40 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 ? Answer: –Event is dispatched only to listeners of appropriate type –Each event type has corresponding event-listener interface Event ID specifies event type that occurred

41 41 Event registration for JTextField textField1.

42 42 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 ActionEvent s when user clicks button

43 43 The Button Hierarchy

44 44 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 textInstantiate JButton with image and rollover image Instantiate ButtonHandler for JButton event handling

45 45 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 Register JButton s to receive events from ButtonHandler When user clicks JButton, ButtonHandler invokes method actionPerformed of all registered listeners

46 46 ButtonTest.java

47 Some Other Components State buttons –On/Off or true / false values –JToggleButton, JCheckBox, and JRadioButton JComboBox (drop-down list) –List of items from which user can select Jlist –Single selection and Multiple Selection JTextArea and JTextField –Multiple lines vs. single line Examples are shown in the last lecture

48 Mouse Event Handling Event-listener interfaces for mouse events –MouseListener –MouseMotionListener –Listen for MouseEvent s

49 MouseListener and MouseMotionListener interface methods

50 1 // MouseTracker.java 2 // Demonstrating mouse events. 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 MouseTracker extends JFrame 12 implements MouseListener, MouseMotionListener { 13 14 private JLabel statusBar; 15 16 // set up GUI and register mouse event handlers 17 public MouseTracker() 18 { 19 super( "Demonstrating Mouse Events" ); 20 21 statusBar = new JLabel(); 22 getContentPane().add( statusBar, BorderLayout.SOUTH ); 23 24 // application listens to its own mouse events 25 addMouseListener( this ); 26 addMouseMotionListener( this ); 27 28 setSize( 275, 100 ); 29 setVisible( true ); 30 } 31 32 // MouseListener event handlers 33 34 // handle event when mouse released immediately after press 35 public void mouseClicked( MouseEvent event ) MouseTracker.java Lines 25-26 Line 35 Register JFrame to receive mouse events Invoked when user presses and releases mouse button

51 36 { 37 statusBar.setText( "Clicked at [" + event.getX() + 38 ", " + event.getY() + "]" ); 39 } 40 41 // handle event when mouse pressed 42 public void mousePressed( MouseEvent event ) 43 { 44 statusBar.setText( "Pressed at [" + event.getX() + 45 ", " + event.getY() + "]" ); 46 } 47 48 // handle event when mouse released after dragging 49 public void mouseReleased( MouseEvent event ) 50 { 51 statusBar.setText( "Released at [" + event.getX() + 52 ", " + event.getY() + "]" ); 53 } 54 55 // handle event when mouse enters area 56 public void mouseEntered( MouseEvent event ) 57 { 58 JOptionPane.showMessageDialog( null, "Mouse in window" ); 59 } 60 61 // handle event when mouse exits area 62 public void mouseExited( MouseEvent event ) 63 { 64 statusBar.setText( "Mouse outside window" ); 65 } 66 67 // MouseMotionListener event handlers 68 69 // handle event when user drags mouse with button pressed 70 public void mouseDragged( MouseEvent event ) MouseTracker.java Line 42 Line 49 Line 56 Line 62 Line 70 Invoked when user presses mouse button Invoked when user releases mouse button after dragging mouse Invoked when mouse cursor enters JFrame Invoked when mouse cursor exits JFrame Invoked when user drags mouse cursor

52 71 { 72 statusBar.setText( "Dragged at [" + event.getX() + 73 ", " + event.getY() + "]" ); 74 } 75 76 // handle event when user moves mouse 77 public void mouseMoved( MouseEvent event ) 78 { 79 statusBar.setText( "Moved at [" + event.getX() + 80 ", " + event.getY() + "]" ); 81 } 82 83 // execute application 84 public static void main( String args[] ) 85 { 86 MouseTracker application = new MouseTracker(); 87 88 application.setDefaultCloseOperation( 89 JFrame.EXIT_ON_CLOSE ); 90 } 91 92 } // end class MouseTracker MouseTracker.java Line 77 Invoked when user moves mouse cursor

53 MouseTracker.java

54 Adapter Classes Adapter class –Implements interface –Abstract –Provides default implementation of each interface method –Used when all methods in interface is not needed

55 Event adapter classes and the interfaces they implement.

56 1 // Painter.java 2 // Using class MouseMotionAdapter. 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 Painter extends JFrame { 12 private int xValue = -10, yValue = -10; 13 14 // set up GUI and register mouse event handler 15 public Painter() 16 { 17 super( "A simple paint program" ); 18 19 // create a label and place it in SOUTH of BorderLayout 20 getContentPane().add( 21 new Label( "Drag the mouse to draw" ), 22 BorderLayout.SOUTH ); 23 24 addMouseMotionListener( 25 26 // anonymous inner class 27 new MouseMotionAdapter() { 28 29 // store drag coordinates and repaint 30 public void mouseDragged( MouseEvent event ) 31 { 32 xValue = event.getX(); 33 yValue = event.getY(); 34 repaint(); 35 } Painter.java Line 24 Lines 30-35 Lines 32-34 Register MouseMotionListener to listen for window’s mouse-motion events Override method mouseDragged, but not method mouseMoved Store coordinates where mouse was dragged, then repaint JFrame

57 36 37 } // end anonymous inner class 38 39 ); // end call to addMouseMotionListener 40 41 setSize( 300, 150 ); 42 setVisible( true ); 43 } 44 45 // draw oval in a 4-by-4 bounding box at the specified 46 // location on the window 47 public void paint( Graphics g ) 48 { 49 // we purposely did not call super.paint( g ) here to 50 // prevent repainting 51 52 g.fillOval( xValue, yValue, 4, 4 ); 53 } 54 55 // execute application 56 public static void main( String args[] ) 57 { 58 Painter application = new Painter(); 59 60 application.addWindowListener( 61 62 // adapter to handle only windowClosing event 63 new WindowAdapter() { 64 65 public void windowClosing( WindowEvent event ) 66 { 67 System.exit( 0 ); 68 } 69 Painter.java Line 52 Draw circle of diameter 4 where user dragged cursor

58 70 } // end anonymous inner class 71 72 ); // end call to addWindowListener 73 } 74 75 } // end class Painter Painter.java

59 Readings Ch 19


Download ppt "1 Review Polymorphism –“having many forms” –Helps build extensible systems Dynamic/late binding –Implements polymorphic processing of objects –Use superclass."

Similar presentations


Ads by Google