Download lab06:gui programming

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Lab 06: Graphical User Interface (GUI) Programming
Objectives:
To gain experience with:




1.
Frames & Window Listener
Drawing graphical shapes in Java Applications
Displaying Images in Java applications
Playing music in Java applications
Drawing graphical shapes in applications:
In ICS102 we learnt how to write applets that display graphical shapes, images and play sound.
We can equally do same and even more with applications. For example, the following is an application
that displays a rectangle.
import java.awt.*;
public class FrameTest {
public static void main(String[] args) {
MyFrame frame = new MyFrame();
frame.setTitle("Graphics Using Frames");
frame.setSize(400, 400);
frame.show();
}
}
class MyFrame extends Frame {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Rectangle rect = new Rectangle (50,50,100,80);
g2.draw(rect);
}
}
The setsize() and setVisible ( ) methods are both defined in the Component
class
f.setSize(400,300)specifies that the frame is 400 pixels wide and 300 pixels
high. If the setSize() method is not used., The frame will be sized at 0x0
pixels, and nothing will be seen except the title bar. The setSize() and
setVisible() methods are both defined in the Component class; therefore,
they are inherited by the Frame class.
Table Event types and corresponding EventSource & EventListener
Event Type
ActionEvent
AdjustmentEvent
ItemEvent
TextEvent
ComponentEvent
ContainerEvent
FocusEvent
KeyEvent
MouseEvent
WindowEvent
Event Source
Button, List, MenuItem, TextField
Scrollbar
Choice, Checkbox, CheckboxMenuItem, List
TextArea, TextField
Component
Container
Component
Component
Component
Window
Event Listener interface
ActionListener
AdjustmentListener
ItemListener
TextListener
Event Listener interface
ActionListener
AdjustmentListener
ItemListener
TextListener
ComponentListener
ContainerListener
FocusListener
KeyListener
MouseListener, MouseMotionListener
WindowListener
Table Event Listener Interfaces and corresponding methods which it defines
Event Listener Methods
actionPerformed(ActionEvent evt)
adjustmentValueChanged(AjustmentEvent evt)
itemStateChanged(ItemEvent evt)
textValueChanged(TextEvent evt)
componentHidden(ComponentEvent evt), componentMoved(ComponentEvent evt),
ComponentListener
componentResized(ComponentEvent evt), componentShown(ComponentEvent evt)
ContainerListener
componentAdded(ContainerEvent evt), componentRemoved(ContainerEvent evt)
FocusListener
focusGained(FocusEvent evt), focusLost(FocusEvent evt)
KeyListener
keyPressed(KeyEvent evt), keyReleased(KeyEvent evt), keyTyped(KeyEvent evt)
mouseClicked(MouseEvent evt), mouseEntered(MouseEvent evt),
MouseListener
mouseExited(MouseEvent evt), mousePressed(MouseEvent evt),
mouseReleased(MouseEvent evt)
MouseMotionListener mouseDragged(MouseEvent evt), mouseMoved(MouseEvent evt)
windowActivated(WindowEvent evt), windowClosed(WindowEvent evt),
windowClosing(WindowEvent evt), windowDeactivated(WindowEvent evt),
WindowListener
windowDeiconified(WindowEvent evt), windowIconified(WindowEvent evt),
windowOpened(WindowEvent evt)
Adapter classes
Event adapters facilitate implementing listener interfaces. Many event listener interfaces have
more than one event listener methods. For such interfaces, Java defines adapter classes. These
have empty implementation (stubs) of all the event listener methods defined in the interface they
implement. A listener can subclass the adapter and override only stub methods for handling events
of interest. The table below lists the low level event listener interfaces and their adapters.
Table Event Listener Interfaces and their corresponding adapter
classes.
Event Listener interface Event Listener Adapter
ComponentListener ComponentAdapter
ContainerListener
ContainerAdapter
FocusListener
FocusAdapter
KeyListener
KeyAdapter
MouseListener
MouseAdapter
MouseMotionListener MouseMotionAdapter
WindowListener
WindowAdapter
1.1
Additional requirements for Applications:
With applets, most of the management tasks are handled by the super class Applet. However, with
applications, the programmer does most of the management himself. For example, the above applications
cannot be terminated by simply clicking the close window button ,“x”.
To close the window, we need to know about the Window handling interface called WindowListener and
how to implement it and add it to the frame.
1.2
WindowLintener Inteface:
This is an interface in the java.awt.event package that specify the methods for controlling a particular
window. It has the following method specifications:
Method
Purpose
windowActivated(WindowEvent e)
Invoked when a window is activated.
windowClosed(WindowEvent e)
Invoked when a window has been closed.
windowClosing(WindowEvent e)
Invoked when a window is in the process of being closed.
windowDeactivated(WindowEvent e)
Invoked when a window is de-activated.
windowDeiconified(WindowEvent e)
Invoked when a window is de-iconified.
windowIconified(WindowEvent e)
Invoked when a window is iconified.
windowOpened(WindowEvent e)
Invoked when a window has been opened.
1.3
WindowAdapter:
Most of the times we do not need all the above methods in our applications, thus we are forced to
implement the ones that we do not need as do nothing methods. Alternatively, we could extends the
WindowAdapter class which is an implementation of WindowListener interface where all the methods
are implemented as do nothing methods. In this way, we only need to override the methods that we need.
The following shows how the windows listener may be implemented so that the application is terminated
when the window is closed.
import java.awt.event.*;
class WindowClosingListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
}
1.4
Adding Window Listener
Once a window event listener is implemented, it can be installed to a frame using its addWindowListener
method. The following shows a modified version of Example1 in which the window can be closed. Notice
that the WindowClosingListener is placed inside the MyFrame class. This is usually how it is done since
most of the times, the listener need to have access to the fields of the class. This is not a problem since the
class only used by the outer class anyway.
Example 1:
import java.awt.*;
import java.awt.event.*;
public class DrawingApplication {
public static void main(String[] args) {
MyFrame frame = new MyFrame();
frame.setTitle("Drawing Using Application");
frame.setSize(400, 400);
frame.show();
}
}
class MyFrame extends Frame {
public MyFrame() {
WindowClosingListener listener = new
WindowClosingListener();
addWindowListener(listener);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Rectangle rect = new Rectangle (50,50,100,80);
g2.draw(rect);
}
//This is an inner class
class WindowClosingListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
}
}
Example
Handling Simple Action Events
console to indicate which button is clicked, when a button is clicked
Example1
.
// TestActionEvent.java: Create a Close button in the frame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TestActionEvent extends JFrame
implements ActionListener
{
// Create an object for "Close" button
private JButton jbtOk = new JButton("OK");
private JButton jbtCancel = new JButton("Cancel");
// Default constructor
public TestActionEvent()
{
// Set the window title
setTitle("TestActionEvent");
// Set FlowLayout manager to arrange the components
// inside the frame
getContentPane().setLayout(new FlowLayout());
// Add buttons to the frame
getContentPane().add(jbtOk);
getContentPane().add(jbtCancel);
// Register listeners
jbtOk.addActionListener(this);
jbtCancel.addActionListener(this);
}
// Main method
public static void main(String[] args)
{
TestActionEvent frame = new TestActionEvent();
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100, 80);
frame.setVisible(true);
}
// This method will be invoked when a button is clicked.
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jbtOk)
{
System.out.println("The OK button is clicked");
}
else if (e.getSource() == jbtCancel)
{
System.out.println("The Cancel button is clicked");
}
}
}
EventObject
User
action
Generate
an event
Notify listener
Trigger an event
Source Object
Register a listener object
2.
Listener Object
Event Handler
Displaying Image
To display an image, we need to first load the image into memory. However, for applications, we need to
make use of the Toolkit class, which is in the java.awt package as follows:
Image image = Toolkit.getDefaultToolkit().getImage(URL of the
image);
Example 2:
import java.awt.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.event.*;
public class ImageApplication {
public static void main(String[] args) {
MyFrame frame = new MyFrame();
frame.setTitle("Image Display Using Application");
frame.setSize(400, 400);
frame.show();
}
}
class MyFrame extends Frame {
private Image image;
public MyFrame() {
WindowClosingListener listener = new
WindowClosingListener();
addWindowListener(listener);
image =
Toolkit.getDefaultToolkit().getImage("kfupmt_wr.jpg");
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(image,50,50,this);
}
class WindowClosingListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
}
}
You can also use the AffineTransform class of the java.awt.geom. package to transform the image
(rotate, translate, etc).
3.
Playing Music
Plying music is slightly more difficult than displaying images.
First we need to use the url of the image file to create a URL object using the URL class of the java.net
package.
While creating the RRL object, we must handle the MalformedURLException which the constructor of
the URL class may generates.
Next we use the static method newAudioClip of the Applet class to create an Audio clip object.
Finally, we use the play, loop and stop method of the AudioClip object to play the music.
Now since it is not wise to reload the audio clip each time the paint method is called, it is a good idea to
implement the windowActivated method of the windowListener and load the audio clip inside that
method.
The following shows how this may be done.
Example 3:
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
import java.net.MalformedURLException;
public class AudioApplication {
public static void main(String[] args) {
MyFrame frame = new MyFrame();
frame.setTitle("Testing Music Application");
frame.setSize(400, 400);
frame.show();
}
}
class MyFrame extends Frame {
AudioClip clip;
public MyFrame() {
WindowClosingListener listener = new
WindowClosingListener();
addWindowListener(listener);
}
public void paint(Graphics g) {
clip.loop();
}
class WindowClosingListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
public void windowActivated(WindowEvent event) {
String relativeURL = "audio/spacemusic.au";
StringBuffer sb=new
StringBuffer(System.getProperty("user.dir"));
for (int i=0; i<sb.length(); i++)
if (sb.charAt(i) == '\\')
sb.setCharAt(i, '/');
String baseURL = "file:///"+ sb + "/";
try {
URL fullURL = new URL(baseURL + relativeURL);
clip = Applet.newAudioClip(fullURL);
}
catch(MalformedURLException
e) {
System.err.println(e.getMessage());
}
}
}
}
Exercise:
1. Compile and Execute the above example programs: use the following image 'kfupmlogo.jpg' and sound
file ' Bismillah.wav’