Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CS 209 Programming in Java #13 Multimedia Part of Textbook Chapter 14 Spring, 2006 Instructor: J.G. Neal 1 Topics • • • • • • • • Multimedia Displaying Images Using the MediaTracker class Images in Applets and Applications Playing Audio Clips Audio Clips in Applets Using the Timer Class for Animation Example Programs 2 Multimedia • Media – Can include images, audio, video, etc. • Java program needs to: – Get the media files – Display/play/pause/replay/stop the media objects • How to handle media in: – Applets – Applications 3 Image Display – Relevant Classes • Relevant classes for getting and displaying Images: 1. Use the Toolkit class and its methods such as getDefaultToolkit and getImage 2. Use the Applet class and its methods such as getCodeBase, getImage 3. Use the Class class and its methods such as getResouce 4. Use the Image class and its methods such as getHeight and getWidth 5. Use the Graphics class and its method drawImage 6. Use the ImageIcon class and its methods such as loadImage and paintIcon 4 Methods Used to Get an Image for Display Methods in the Applet class • Get base URL – URL getCodeBase() - Gets the base URL for folder – URL getDocumentBase() - Returns an absolute URL for the document in which the applet is embedded • Get the image – public Image getImage(URL url) – public Image getImage(URL url, String filename) 5 Getting Images in a Java Program Approach 1: • • Use JApplet methods getCodeBase and getImage Example: String imagePath0 = "images/dukeWave.gif"; String imagePath1 = "images/duke2.gif"; img0 = getImage(getCodeBase(), imagePath0); img1 = getImage(getCodeBase(), imagePath1); try { mt.addImage(img0, 0); mt.addImage(img1, 0); mt.waitForID(0); } catch (Exception ex) { System.out.println("\n" + ex.toString()); } 6 Getting Images in a Java Program Approach 2: • • Use the URL class and method getResource from class Class Example: String imagePath0a = "../images/dukeWave.gif"; String imagePath1a = "../images/duke2.gif"; Class object = this.getClass(); URL url0 = object.getResource(imagePath0a); URL url1 = object.getResource(imagePath1a); System.out.println("url0 = " + url0.toString()); System.out.println("url1 = " + url1.toString()); if ((url0 != null) && (url1 != null)) { img0 = getImage(url0); img1 = getImage(url1); try { mt.addImage(img0, 0); mt.addImage(img1, 0); mt.waitForID(0); } catch (Exception ex) { System.out.println("\n" + ex.toString()); } } 7 Getting Images in a Java Program Approach 3: • Use the Toolkit class – Static Toolkit getDefaultToolkit() - Gets the default AWT toolkit – Image getImage(String filename) - Returns an image which gets pixel data from the specified file, whose format can be either GIF, JPEG or PNG – Image getImage(URL url) - Returns an image which gets pixel data from the specified URL – Also has methods to: • Get the screen resolution in dots-per-inch • Get the screen size • Get the system clipboard • Among others • Example: img[i] = Toolkit.getDefaultToolkit().getImage(imgFileName); 8 Displaying Images Using Graphics Methods Methods in the Graphics class to draw the image • drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) - Draws the image in the specified location. The image’s upper left corner is at (x, y) in the coordinate space of the graphics context. Transparent pixels are drawn in the bgcolor. The observer is the object on which the image is displayed. The image is cut off if it is larger than the area upon which it is drawn. • drawImage(Image img, int x, int y, ImageObserver observer) - Same as above, but no bgcolor. • drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) - Draws a scaled version of the image. • drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) - Same as above, but includes background color. 9 MediaTracker Class • A utility class to track the status of media objects – In the package: java.awt – Use the import statement: import java.awt.MediaTracker; – Or use import statement: import java.awt.*; • Media objects – Could include images, audio clips, etc. – As of j2sdk1.4.0, only images were supported (continued on next slide) 10 MediaTracker Class (cont.) To use a MediaTracker: • Create an instance of the MediaTracker class • Call the MediaTracker addImage method for each image to be tracked – MediaTracker(Component c) - Track for component c • – addImage(Image image, int id) - adds an image to the list of images being tracked by this media tracker – addImage(Image image, int id, int w, int h) - adds a scaled image to the list of images being tracked by this tracker Call the MediaTracker checkAll method – checkAll() - checks to see if all images being tracked by this media tracker have finished loading; does not start loading any images – checkAll(boolean load) - checks to see if all images being tracked by this media tracker have finished loading; if the parameter is true, this method starts loading any images that are not yet being loaded (continued on next slide) 11 MediaTracker Class (cont.) • • Each image can be assigned a priority level identifier ID – The ID controls the priority order in which images are fetched – The ID is commonly not unique per image – Images with a lower ID are loaded in preference to those with a higher ID number Call one of the “wait” methods to control processing – void waitForAll() - starts loading all tracked images; waits until all the images being tracked have finished loading – void waitForID(int id) - starts loading all tracked images with specified ID (priority level); waits until all the images with the specified ID have finished loading 12 Example Java Program • Purpose: To demonstrate – Use of images in a Java program – Providing adequate display area and scroll capabilities • Program: – Class name: ImageEx – Package name: mymediaexs – Project name: MyMediaExs • Program code: – See next pages 13 Example Program Execution 14 Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\MyMedia\MyMediaExs\src\mymediaexs\ImageEx.java at 4/27/06 5:16 1 package 2 3 import 4 import 5 import 6 import 7 8 public class ImageEx extends JFrame { 9 // Instance variables 10 private 11 private 12 private 13 14 private Image img = null 15 private MediaTracker mt = new MediaTracker( this 16 private int 17 private float 18 private float 19 20 // The main method required for an application program 21 public static void main( String[] args ) { // Construct the window 22 JFrame frame = new ImageEx 23 frame.setSize(new Dimension 24 frame.setDefaultCloseOperation 25 frame.setVisible( true // Make the window visible 26 } 27 28 public ImageEx() { 29 super 30 Container c = getContentPane // Get content pane for JFrame window // Set layout manager for 31 c.setLayout( new BorderLayout window 32 CanvasPanel cPan = new CanvasPanel 33 34 img = Toolkit.getDefaultToolkit().getImage 35 try { 36 mt.addImage 37 mt.waitForID 38 System.out.println 39 } catch ( Exception ex ) { 40 System.out.println( "\n" + ex.toString 41 } 42 h = img.getHeight( null 43 w = img.getWidth( null 44 cPan.setPreferredSize( new Dimension( Math.round(scaleFactorUp * w), 45 Math.round((scaleFactorUp + Page 1 Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\MyMedia\MyMediaExs\src\mymediaexs\ImageEx.java at 4/27/06 5:16 46 cPan.setVisible( true 47 JScrollPane jscrollpane = new JScrollPane(cPan, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 c.add } // Class to provide a drawing surface for graphics display class CanvasPanel extends JPanel { // Constructor public CanvasPanel() { setBackground } public void paintComponent ( Graphics g ) { super.paintComponent int int int g.drawString( "Image Width: " + w + ", Height: " + h, xPos, yPos 65 g.drawImage( img, xPos, yPos + sp, null 66 67 // Draw scaled down version of image using method drawImage 68 int wDown = Math.round 69 int hDown = Math.round 70 g.drawString( "Image scaled down by factor of: " + scaleFactorDown + 71 ", Width: " + wDown + ", Height: " + hDown, 73 g.drawImage( img, xPos, 5*sp + h, wDown, hDown, null 74 75 // Create new scaled up version of image and draw it 76 int wUp = Math.round 77 int hUp = Math.round 78 g.drawString( "Image scaled up by factor of: " + scaleFactorUp + 79 ", Width: " + w*scaleFactorUp + ", Height: " + h*scaleFactorUp, 81 82 83 84 } 85 g.drawImage( img, xPos, 8*sp + h + hDown, wUp, hUp, null } } // End canvasPanel class Page 2 Displaying Images Using the ImageIcon Class Constructors and methods in the ImageIcon class • Create an ImageIcon – ImageIcon(Image img) - Creates ImageIcon from Image object – ImageIcon(String filename) - Creates ImageIcon from file – ImageIcon(URL url) - Creates ImageIcon from url • Methods in the ImageIcon class – int getIconHeight() - Gets height of ImageIcon object – int getIconWidth() - Gets width of ImageIcon object – void loadImage(Image img) - Loads image, returning when load is complete – void paintIcon(Component c, Graphics g, int x, int y) - Paints the icon 15 Create New Component to Display Image Various components can display images • Using the JLabel class – – – – • JLabel(Icon icon) JLabel(Icon icon, int hAlignment) JLabel(String text, Icon icon, int hAlignment) void setIcon(Icon icon) Using the JButton class – JButton(Icon icon) – JButton(String text, Icon icon) 16 Example Program • Purpose: To demonstrate – Use of an application program and – Use of images in the graphical user interface • Program: – Class name: TextCompEx2Done – Package name: widgetexs – Project name: WidgetExs • Questions: – Can an image be replaced during runtime? If so, how? 17 Example Program 18 Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\GuiDev\WidgetExs\src\widgetexs\TextCompEx2Done.java at 4/28/06 1 package 2 3 import 4 import 5 import 6 import 7 import 8 9 public class TextCompEx2Done extends JFrame implements ActionListener, ItemListener { 10 // Declare instance variables 11 private // Explanatory info for user 12 private 13 private //JCheckBox for setting line wrap // The JComboBox for font selection 14 private //JCheckBoxes for two font 15 private styles // The JComboBox for font size selection 16 private // Display area for text 17 private 18 // The color defined by user 19 private 20 private int 21 private int 22 private 23 private Font selectedFont = new Font(selectedFace, selectedStyle, 25 private String fontNames[] = { 27 private String fontSizes[] = { 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 // The main method required for an application program public static void main(String[] args) { JFrame frame = new TextCompEx2Done // Construct the window frame.setSize(new Dimension // Set its size frame.setDefaultCloseOperation frame.setVisible(true // Make the window visible } public TextCompEx2Done() { // Call parent constructor and set title in title bar of window super Container c = getContentPane // Get reference to content pane // Set layout for content pane c.setLayout(new BorderLayout JPanel jpan = new JPanel(new GridLayout // Create JComboBoxes for user selection of font and font size Page 1 Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\GuiDev\WidgetExs\src\widgetexs\TextCompEx2Done.java at 4/28/06 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 editing 90 91 92 93 jcboxFont = new JComboBox jcboxFont.addItemListener(this jpan.add jcboxSize = new JComboBox jcboxSize.setMaximumRowCount jcboxSize.addItemListener(this jpan.add // Create JButton for user to choose text color colorItem = new JButton colorItem.addActionListener(this jpan.add // Create JCheckBox to enable user to line wrap on/off linewrap = new JCheckBox("Line Wrap", false linewrap.addItemListener(this jpan.add // Create JCheckBoxes for two font styles, but not as a group fstyleBold = new JCheckBox("Bold", false fstyleBold.addItemListener(this jpan.add fstyleItalic = new JCheckBox("Italic", false fstyleItalic.addItemListener(this jpan.add c.add // Get and display images for decorative purposes URL url1 = this.getClass().getResource JLabel jlabel1 = new JLabel(new ImageIcon jlabel1.setBorder(new EtchedBorder c.add URL url2 = this.getClass().getResource JLabel jlabel2 = new JLabel(new ImageIcon jlabel2.setBorder(new EtchedBorder c.add // Create and add the JTextArea to be used for text display and textArea = new JTextArea textArea.setFont textArea.setLineWrap(false textArea.setBorder(new TitledBorder Page 2 Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\GuiDev\WidgetExs\src\widgetexs\TextCompEx2Done.java at 4/28/06 94 95 96 97 98 99 100 JScrollPane jspane = new JScrollPane c.add } public void actionPerformed(ActionEvent e) { if (e.getSource() == colorItem) { Color returnedColor = JColorChooser.showDialog(this, 102 104 105 106 107 108 109 110 111 112 113 114 116 117 if (returnedColor != null) { textArea.setForeground } } } public void itemStateChanged(ItemEvent e) { // If the JCheckBox for Bold style was clicked, set the applet's font // style based on whether Bold was selected or deselected if (e.getSource() == fstyleBold) if (e.getStateChange() == ItemEvent.SELECTED) else if (e.getStateChange() == ItemEvent.DESELECTED) 119 120 // If the JCheckBox for Italic style was clicked, set the applet's font 121 // style based on whether Italic was selected or deselected 122 if (e.getSource() == fstyleItalic) 123 if (e.getStateChange() == ItemEvent.SELECTED) 125 126 128 129 130 131 132 133 134 135 136 137 138 139 140 else if (e.getStateChange() == ItemEvent.DESELECTED) // If the JCheckBox for line wrap was selected or not, set // the JTextArea's line wrap accordingly if (e.getSource() == linewrap) if (e.getStateChange() == ItemEvent.SELECTED) textArea.setLineWrap(true else if (e.getStateChange() == ItemEvent.DESELECTED) textArea.setLineWrap(false // If one of the items in the JComboBox was selected, // set the fontname variable to the user's selection if (e.getSource() == jcboxFont) { Page 3 Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\GuiDev\WidgetExs\src\widgetexs\TextCompEx2Done.java at 4/28/06 141 selectedFace = fontNames[jcboxFont.getSelectedIndex 142 } 143 144 if (e.getSource() == jcboxSize) { 145 selectedSize = Integer.parseInt(fontSizes[jcboxSize. getSelectedIndex 146 } 147 148 textArea.setFont(new Font(selectedFace, selectedStyle, 149 } 150 151 } Page 4 Using Audio Clips Methods in the Applet class • Methods for using audio clips – AudioClip getAudioClip(URL url) - Returns the AudioClip object specified by the url; always returns immediately; data loaded when attempt to play is made – static AudioClip newAudioClip(URL url) - Returns the AudioClip object specified by the url Methods in the AudioClip interface class • Methods for using audio clips – void play() - Plays this audio clip starting from the beginning – void loop() - Plays this audio clip in a loop starting at beginning – void stop() - Stops playing this audio clip 19 Example Program • Purpose: To demonstrate – Use of an applet program and – Use of audio and images in the graphical user interface • Program: – Class name: FlagAnthem – Package name: mediaexs – Project name: MediaExs • Code is available on instructor’s webpage • Questions: – What are some problems or shortcomings of this program? 20 Example Program 21 Timer Class Purpose • • • Has a specified delay time interval, and repeatedly fires an action event once per time interval (e.g., once per second) The delay time interval is the time between action events For example, an animation object can use a Timer as the trigger for drawing its frames Setting up a Timer involves 1. Creating a Timer object, 2. Registering one or more action listeners on it, and 3. Starting the timer using the start method 22 Timer Class Selected constructors and methods • Constructor – Timer(int delay, ActionListener listener) - Creates a Timer that will notify its listeners every delay milliseconds • Methods – void setDelay(int delay) - Sets the Timer’s delay, the number of milliseconds between successive action events – void start() - Starts the Timer, causing it to start sending action events to its listeners – void stop() - Stops the Timer, causing it to stop sending action events to its listeners 23 Example Program • Purpose: To demonstrate – Use of an application program and – Use of a Timer object to implement animation • Program: – Class name: ApplicWTimer – Package name: mymediaexs – Project name: MyMediaExs • Questions: – How would you vary (e.g., slow down or speed up) the rate at which the images appear to move across the applet? 24 Example Program 25 Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\MyMedia\MyMediaExs\src\mymediaexs\ApplicWTimer.java at 4/28/06 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 package import import import import import public class ApplicWTimer extends JFrame implements ActionListener { private private String fName[] = {"Assets.gif", "Contacts.gif", "Evtmgmt. private private private private private private int int Image img[] = new MediaTracker mt = new MediaTracker(this private int private int private private private private private private int int int int int Timer timer = new Timer(15, this // The main method required for an application program public static void main( String[] args ) { // Construct the window JFrame frame = new ApplicWTimer frame.setDefaultCloseOperation frame.setVisible( true // Make the window visible } /** Creates a new instance of ApplicWTimer */ public ApplicWTimer() { super Container c = getContentPane setSize( new Dimension c.setLayout(new BorderLayout setBackground // Create a panel to display moving banner imgPan = new ImagePanel imgPan.setBorder(new EtchedBorder imgPan.setBorder(new TitledBorder("Demonstration of Timer-Based Page 1 Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\MyMedia\MyMediaExs\src\mymediaexs\ApplicWTimer.java at 4/28/06 47 48 49 50 51 52 53 54 55 56 57 58 59 c.add timer.start } public void actionPerformed(ActionEvent e) { imgPan.repaint } public class ImagePanel extends JPanel { int // Constructor public ImagePanel(int w) { 61 62 // Get images and assign into array for (int 64 img[i] = Toolkit.getDefaultToolkit().getImage 65 try { 66 mt.addImage 67 mt.waitForID 68 } catch (Exception ex) { 69 System.out.println("\n" + ex.toString 70 } 71 } 72 73 set image width and height variables 74 imgWidth = img[0].getWidth(null 75 imgHeight = img[0].getHeight(null 76 77 setBackground 78 setPreferredSize(new Dimension(apWidth, imgHeight + yPos * 79 80 81 82 83 84 85 86 87 88 89 91 setVisible(true } // Paint the JPanel public void paintComponent(Graphics g) { super.paintComponent int int // Create and draw image while (xPos < panelWidth) { g.drawImage(img[currentImgIndex], xPos, yPos, null Page 2 Printing C:\Documents and Settings\jgneal\My Documents\MyDev\MyJava\MyMedia\MyMediaExs\src\mymediaexs\ApplicWTimer.java at 4/28/06 93 } 94 95 // Establish the horizontal start position for the next repaint of banner 96 // and the image with which to start 98 99 100 if (startXPos > betweenSpace) { 102 /* 103 104 105 106 */ if (startImageIndex < 0) 108 if (startImgIndex >= fName.length) 110 111 112 113 114 } 115 } } // End paintComponent } Page 3