Transcript LECT#14
Applications of Graphics
Overview
Conversions Between Applications and Applets
Handling Mouse Events
Handling Keyboard Events
Example Keyboard Events Demo
Audio Files.
Example Using Audio Clips
Lecturte 14Lecture 7
1
Conversions Between Applications and Applets
Conversions between applications and applets are simple and easy.
You can always convert an applet into an application.
You can convert an application to an
applet as long as security restrictions are
not violated.
Converting Applications into Applets
1- Drop the class with the main method that shows the frame
2- Inherit from Japplet, not Jframe
3-Remove the window listener
4 Remove the call to setsize and instead set the size in the applet’s HTML page
5- Remove the call to setTitle
Lecturte 14Lecture 7
2
More on Handling Mouse Events
Java provides two listener interfaces, MouseListener
and MouseMotionListener, to handle mouse events.
The MouseListener listens for actions such as when the
mouse is pressed, released, entered, exited, or
clicked.
The MouseMotionListener listens for
actions such as dragging or moving the
mouse.
Lecturte 14Lecture 7
3
Example Moving message using Mouse
// MoveMessageDemo.java: Move a message in a panel
// by dragging the mouse
// Place the message panel in the frame
getContentPane().setLayout(new
BorderLayout());
getContentPane().add(p);
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MoveMessageDemo
extends JApplet
{
// Initialize the applet
public void init()
{
// Create a MoveMessagePanel
// This main method enables the applet to run as an application
public static void main(String[] args)
{
// Create a frame
instance for drawing a message
JFrame frame = new JFrame("Move
Message Using Mouse");
MoveMessagePanel p = new
MoveMessagePanel("Welcome to
Java");
Lecturte 14Lecture 7
4
MoveMessageDemo
// Create an instance of the applet
MoveMessageDemo applet = new MoveMessageDemo();
// Tell the panel how to draw things
public void paintComponent(Graphics g)
frame.getContentPane().add(applet, BorderLayout.CENTER);
{
// Invoke init() and start()
// Invoke the paintComponent method in the
applet.init();
MessagePanel class
applet.start();
super.paintComponent(g);
// Display the frame
}
frame.setSize(300, 300);
// Handler for mouse moved event
//
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLO
public void mouseMoved(MouseEvent e)
SE);
{
frame.setVisible(true);
}
}
// Handler for mouse dragged event
// MoveMessagePanel draws a message
// This class is defined as inner class
public void mouseDragged(MouseEvent e)
class MoveMessagePanel extends MessagePanel
{
implements MouseMotionListener
// Get the new location and repaint the screen
{
setXCoordinate(e.getX());
// Construct a panel to draw string s
setYCoordinate(e.getY());
public MoveMessagePanel(String s)
repaint();
{
super(s);
}
this.addMouseMotionListener(this);
}
5
// Add the applet instance to the frame
}
Lecturte 14Lecture 7
More Handling Keyboard Events
Handling Keyboard Events
To process a keyboard event, use the following handlers in the KeyListener
interface:
keyPressed(KeyEvent e)
Called when a key is pressed.
keyReleased(KeyEvent
e)
Called when a key is released.
keyTyped(KeyEvent
e)
Called when a key is pressed and then
released
Lecturte 14Lecture 7
6
The KeyEvent Class
Methods:
getKeyChar() method
getKeyCode()
method
Keys:
Home
End
Page Up
Page Down
The enter key
VK_HOME
VK_End
VK_PGUP
VK_PGDN
VK_ENTER
etc...
Lecturte 14Lecture 7
7
Example Keyboard Events Demo
Objective: Display a user-input character. The user can also move the character up, down,
left, and right using the arrow keys.
// KeyboardEventDemo.java: Receive key input
public static void main(String[] args)
{
import java.awt.*;
import java.awt.event.*;
// Create a frame
import javax.swing.*;
JFrame frame = new
public class KeyboardEventDemo
JFrame("KeyboardEvent Demo");
extends JApplet
// Create an instance of the applet
{
KeyboardEventDemo applet = new
private KeyboardPanel keyboardPanel = KeyboardEventDemo();
new KeyboardPanel();
// Add the applet instance to the frame
// Main method used if run as an application
frame.getContentPane().add(applet,
BorderLayout.CENTER);
// Invoke init() and start()
applet.init();
applet.start();
Lecturte 14Lecture 7
8
Example Keyboard Event (Cont)
// Request focus
focus();
}
// Set focus on the panel
public void focus()
{
// Display the frame
frame.setSize(300, 300);
//
frame.setDefaultCloseOperation(JFrame.
EXIT_ON_CLOSE);
frame.setVisible(true);
// It is required for receiving key input
// Set focus on the keyboardPanel
keyboardPanel.requestFocus();
applet.focus();
}
}
// Initialize UI
public void init()
{
}
// Add the keyboard panel to accept and display user input
getContentPane().add(keyboardPanel);
Lecturte 14Lecture 7
9
Example Keyboard Event (Cont)
// KeyboardPanel for receiving key input
class KeyboardPanel extends JPanel implements KeyListener
{
private int x = 100;
private int y = 100;
private char keyChar = 'A'; // Default key
public KeyboardPanel()
{
addKeyListener(this); // Register listener
}
public void keyReleased(KeyEvent e)
{
}
Lecturte 14Lecture 7
10
Example Keyboard Event (Cont)
public void keyTyped(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_DOWN: y +=
10; break;
case KeyEvent.VK_UP: y -= 10;
break;
case KeyEvent.VK_LEFT: x -= 10;
break;
case KeyEvent.VK_RIGHT: x += 10;
break;
default: keyChar = e.getKeyChar();
}
repaint();
}
// Draw the character
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setFont(new Font("TimesRoman",
Font.PLAIN, 24));
g.drawString(String.valueOf(keyChar),
x, y);
}
}
Lecturte 14Lecture 7
11
Audio Files
Audio is stored in files. There are several formats of audio
files. JDK 1.2 can play several audio file formats,
including .wav and .au files.
play(URL
url, String filename);
Plays the audio clip after it is given the URL and the file name that is
relative to the URL. Nothing happens if the audio file cannot be found.
play(getCodeBase(),
"soundfile.au");
Plays the sound file soundfile.au, located in the applet’s directory.
play(getDocumentBase(),
"soundfile.au");
Plays the sound file soundfile.au, located in the
HTML file’s directory.
Lecturte 14Lecture 7
12
Using Audio Clips
public AudioClip getAudioClip(URL url);
public AudioClip getAudioClip(URL url,
String name);
Either method creates an audio clip. Specify String
name to use a relative URL address.
public abstract void play()
public abstract void loop()
public abstract void stop()
Use these methods to start the clip, play it
repeatedly, and stop the clip, respectively.
Lecturte 14Lecture 7
13
example displays images and continuously play a sound clip
until the applet window is closed
import java.awt.Graphics;
import java.awt.Image;
import java.applet.AudioClip;
/* plays audio sound and displays image */
public class AudioSound extends java.applet.Applet {
AudioClip nachid;
public void init() {
nachid = getAudioClip(getDocumentBase(),
"salam_al_malaki.au");
}
public void paint(Graphics g) {
nachid.loop(); // Looping the salam_al_malaki audio file !!!
}
}
Lecturte 14Lecture 7
14
Example of playing sound
import java.applet.AudioClip;
class MyFrame extends Frame {
import java.applet.Applet;
private Image im;
import java.awt.*;
public MyFrame() {
import java.net.URL;
setTitle("Audio Using Frames");
import java.net.MalformedURLException;
setSize(400,400);
} // End of MyFrame() constructor
public class AudioTest1 {
public void paint(Graphics g) {
public static void main(String[] args) {
String relativeURL = " spacemusic.au
";
MyFrame frame = new MyFrame();
AudioClip audio;
frame.show();
//String relativeURL = "spacemusic";
} // End of main method
URL baseURL = null; // Initialize the
} // End of class AudioTest1
URL reference
URL completeURL = null;
//
Initialize the URL reference
Lecturte 14Lecture 7
15
Example (Cont.)
try {
baseURL = new URL("file:" +
System.getProperty("user.dir") + "/"); //
Finding out the File System Type
}
catch (MalformedURLException e) {
System.err.println(e.getMessage());
}
try {
completeURL = new
URL(baseURL, relativeURL);
}
catch (MalformedURLException e){
System.err.println(e.getMessage());
}
audio =
Applet.newAudioClip(completeURL);
audio.loop(); // Playing the sound file
in a loop
} // End of paint() method
} // End of MyFrame class
Lecturte 14Lecture 7
16