threading+gui intro
DESCRIPTION
TRANSCRIPT
join method
• final void join() throws interruptedException• join() method allows the thread to wait until the
thread on which it was called terminates.• Calling thread waits until the specified thread
joins.
Suspending , Resuming and Stopping Threads
• Prior to Java 2 we can use
final void suspend();
final void resume();
• In Java 2(we provide methods in the Thread class itself)
Example Suspending Resuming in Java 2
class SampleThread extends Thread{…………………………….boolean suspendFlag=false;public void run(){try {syncronized(this) { while(suspendFlag) wait(); }……………………………………………………..}catch(InterruptedException e) { }}
void mySuspend() { suspendFlag = true; }
synchronized void myResume() { suspendFlag = false; }} // end of thread class
Event Handling
Event• Object that describes a state change in source• e.g Pressing a Button generates Action Event
[ Button is source of Event, Name of the event is Action]
• Every event has a source whose state change causes the event
• Some of the activities that may result in event generation:
1. Pressing a Button2. Entering a Character from keyboard3. Selecting an item in a list4. Clicking the mouse5. Timer expires6. Counter Exceeds
Event Source
• Source is an object that generates an event• Internal state of the source changes in some way• When ever source generates an event it is notified to one or
more listeners• Source must register one or more listeners via following
methods:
1. public void addTypeListener(TypeListener el)2. public void addTypeListener(TypeListener el) throws
java.util.TooManyListnersException
• Second Form allows only single listener to attached to the source.
• <<Type>> is the type of the Event
Event Listeners
• Object That is notified whenever source generates a particular type of event
• Responsibilities
1. Must register with the source
2. Must implement desired Listener interface
Delegation Event Model
• Modern Approach for event handling• Three components
1. Source [Object which generates the event]
2. Event [ Object that indicates state change in Source]
3. Listener [ Notified Object which carries out some action whenever event is generated]
• Source generates a particular type of event and it notifies the listener
• On receiving notification from source listener carries out the desired task
9
Java AWT event delegation model
Java automatically generates event objects whenMouse or button clickedMenu, checkbox, or text selectedKeyboard typedScrollbar adjusted
…..
It is up to the programmer to decide whether to do anything or what to do when an event happens
10
• Event source: – An object that generates events
• Listener: – Receives events and decides what to do
Java AWT event delegation model
Event Listener Event Source
Event Object evt
11
• A listener must be registered with an event source in order to listen for events produced there.
• An event source can have multiple listeners and vice versa
– A listener class must implement a listener interface, which decides the response to an event.
Java AWT event delegation model
12
Java AWT event delegation model
Any objects of class that implements an appropriate listener interfaceclass Listener implements ActionListener { … actionPerformed(Event evt) {…}}
Has to register its own listeners
Source.addActionListener(Listener)
Event Listener Event Source
Event Object evt
13
• The event handling process:– When an event occurs, event source sends event
objects to all registered listeners.
– Listeners use information encapsulated in the event objects to determine what to do.
Java AWT event delegation model
Event Listener Event Source
Event Object evt
Examples of Events1. ActionEvent
(a) When Button is Pressed
(b) When List Item is double-clicked
(c) Menu Item is selected
2. AdjustmentEvent
(a) Scroll Bar manipulated
3. ComponentEvent
(a) Component is hidden, moved, resized or becomes visible
4. ContainerEvent
(a) Whenever a component is added or removed from container
5. FocusEvent
(a) When ever component gains or lose keyboard focus
6 Mouse Event
(a) Mouse Dragged , moved, clicked, pressed or released
Event Sources Examples
• User interface components that can generate events1. Button (ActionEvent)2. Checkbox (ItemEvent)3. Choice (ItemEvent)4. List (ActionEvent, ItemEvent)5. MenuItem (ActionEvent, ItemEvent)6. Scrollbar (AdjustmentEvent)7. Window (WindowEvent)
Event Classes
• EventObject (Super Class for for all events, java.util.*)
• AWTEvent (Subclass of EventObject, Superclass of all AWT based events)
• Package java.awt.event defines event classes
• Examples : ActionEvent, ContainerEvent, FocusEvent
Event Listener Interfaces
• Listener must implement suitable event listener interface in order to execute the code whenever that type of event is generated
• What happens when an event occurs?
1. Suitable Event object is created
2. Source invokes the appropriate method provided by the listener by passing the object created in step1 as parameter
• Examples : ActionListener, MouseListner, MouseMotionListener
ActionListener Interface
public interface ActionListener
{
public void actionPerformed(ActionEvent ae);
}
MouseListener
public interface MouseListener
{
public void mouseClicked(MouseEvent me);
public void mouseEntered(MouseEvent me);
public void mouseExited(MouseEvent me);
public void mousePressed(MouseEvent me);
public void mouseReleased(MouseEvent me);
}
MouseMotionListener extends MouseListenerpublic interface MouseListener extends MouseMotionListener
{
public void mouseMoved(MouseEvent me);
public void mouseDragged(MouseEvent me);
}
Graphics
• Mostly the classes graphics category are in two packages
1. java.awt.*2. javax.swing.*; [ All classes in this package starts
with letter J]• Graphics Programming in Java is Component
oriented.
Partial View of Graphics class Hierarchy
Object
Color
Graphics
Component
Button
Checkbox
Convas
ContainerJComponent
Window
Panel
FrameJFrame
JAppletApplet
Graphics2D
BorderLayoutFlowLayoutBoxLayoutGridLayoutCardLayout
GridBagLayout
Layout managers for containers
AbstractButton
JButtonJPanel
JFrame in Java• An actual Window having Title Bar, Menu Bar, Borders and resizing
corners.
• Imporatant Constructors :
1. JFrame() Constructs a new frame that is initially invisible.
2. JFrame(String title) Creates a new, initially invisible Frame with the specified title.
• Important Methods :
1. Container getContentPane() Returns the contentPane object for this frame.
2. void setLayout(LayoutManager manager) Sets the LayoutManager.
3. void setDefaultCloseOperation(int operation)
4. void setSize(FRAME_WIDTH,FRAME_HEIGHT)
5. void show(); - shows the frame Now Deprecated
6. setVisible(true/false); // Actual Method Java 2 for displaying Frames.
JFrame Examples
• JFrame f1 = new JFrame(); // Creates a Frame with no title• JFrame f2 = new JFrame(“My Frame”); // Frame with Title “MY
Frame”• f1.setSize(400,600); // sets size to 400 by 600 pixels• f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
(Program Terminates when Frame Window is closed) • Adding Components to JFrame (Upto 1.4.2)
Conatiner c1 = f1.getContentPane();
c1.setLayout(……….);
c1.add(<Component>);• In Java 1.5 (No need to get ContentPane)
f1.add(<Component>);
JPanel class in Java
• Is just like a Frame window without Borders and a Title.
• Flat panel window acts a light weight container
• Constructors 1. JPanel()
Creates a new JPanel with a double buffer and a flow layout.
2. JPanel(LayoutManager layout) Create a new buffered JPanel with the specified layout manager
JLabel Objects in Java
1. Display text or image or both in Java Graphics
2. Constructors :
• JLabel()
• JLabel(Icon image)
• JLabel(String text)
3. Important Methods :
• setIcon(Icon icon);
• setText(String text);
• setSize(width,height);
• setForeground(Color.red);
Java.awt.Color class
• Every Component can set foreground and background colors.
1. public void setBackground(java.awt.Color c)
2. public void setForeground(java.awt.Color c)
• Colors can be set by passing arguments as :
Color.red
Color.black
Color.green
Layout Managers• Arrangements of several components within a container is
called layout.• Conatiner’s layout can be set by passing LayoutManager
object to setLayout() method.• Some basic Layouts :
1. FlowLayout :
“Lays out components left to right and then starts from new row when there is not enough room in the current one.”
2. BOXLayout :
“ Lays out components horizontally or vertically”
3. BorderLayout :
This layout has five areas for laying out. NORTH,SOUTH,EAST,WEST and CENTER.
• GridLayout :
“ Arraganges Components in a rectangular grid. All Components are resized to an identical size”.
• GridBagLayout:
“ Also Arraganges Components in a grid but rows and columns can have different sizes andcomponents can span multiple rows and columns”.
Layout Managers continued…
JTextField class
• A text field is a text component that displays editable text.• Standard mechanism for input into graphics program.• Constructors :
JTextField()
JTextField(String text)
JTextField(int columns)
JTextField(String text, int columns)
Icon Interface
• Used to create and define icons.
public interface Icon
{
public int getIconHeight();
public int getIconWidth();
public void paintIcon(Component c, Graphics g, int x, int y)
}
•Graphics Parameter carries out the Drawing operation.
•To use more powerful 2D drawing operations we have to type case to Graphics2D
Icon interface ….
• paintIcon method receives graphics context of type Graphics
• Actually a Graphics2D object in modern Java versions
• public void paintIcon(Component c, Graphics g, int x, int y){Graphics2D g2 = (Graphics2D)g;. . .}
Drawing Shapes
• We can draw objects of any class that implements shape interface
Drawing shapes ….
Shape s = …….
g2.draw(s);
Shape s = new Rectangle2D.Double(x,y,width,height);
g2.draw(s); // Rectangle will be drawn
Shape s = new Ellipse2D.Double(x,y,width,height);
g2.draw(s); // Ellipse will be drawn
Shape s = new Rectangle2D.Double(x,y,width,width);
g2.draw(s); // Circle will be drawn
Drawing shapes cont….
Point2D.Double start = new Point2D.Double(x1,y1);
Point2D.Double end = new Point2D.Double(x1,y1);
Shape s1 = new Line2D.Double(start,end);
g2.draw(s1);
Example 1 Circle Icon
class circleicon implements Icon{private int size; // radiuscircleicon(int radius) { size = radius;}public int getIconHeight() { return size;}public int getIconWidth() { return size;}public void paintIcon(Component c, Graphics g, int x,int y){Graphics2D g2 = (Graphics2D) g;Ellipse2D.Double circle = new Ellipse2D.Double(x,y,size,size);g2.draw(circle);}}
Example 2 RectangleIconclass recticon implements Icon{private int height;private int width;recticon(int height,int witdh) { this.height = height;this.width = width;}public int getIconHeight() { return height;}public int getIconWidth() { return width;}public void paintIcon(Component c, Graphics g, int x,int y){Graphics2D g2 = (Graphics2D) g;Rectangle2D.Double r1 = new Rectangle2D.Double(5,5,x-width,y-height);g2.draw(r1);}}
Example
Hello Hi
RED
GREEN
<< Hello How are You>>
import java.awt.*;import javax.swing.*;
class MainFrameTest{public static void main(String args[]){// Creating Frame Window with title Main Frame and setting size and layoutJFrame frame = new JFrame("Main Frame");frame.setSize(400,600);frame.setLayout(new BorderLayout());
// color button PanelJPanel colorButtonPanel = new JPanel();colorButtonPanel.setLayout(new BoxLayout(colorButtonPanel,BoxLayout.Y_AXIS));
// text button PanelJPanel textButtonPanel = new JPanel();
// label display panelJPanel labelDisplayPanel = new JPanel();labelDisplayPanel.setLayout(new BorderLayout());
// label to be displayed JLabel displayLabel =new JLabel("Hello How are you");// Add displayLabel to labelDisplayPanellabelDisplayPanel.add(displayLabel,BorderLayout.CENTER); // Creating buttonsJButton red = new JButton("RED");JButton green = new JButton("GREEN");JButton hello = new JButton("Hello");JButton hi = new JButton("Hi");// Addings red and green buttons to color panelcolorButtonPanel.add(red);colorButtonPanel.add(green);// Adding text buttons to textButton PanelstextButtonPanel.add(hello);textButtonPanel.add(hi);// adding panels to frameframe.add(labelDisplayPanel,BorderLayout.CENTER);frame.add(colorButtonPanel,BorderLayout.EAST);frame.add(textButtonPanel,BorderLayout.SOUTH);// Displaying Frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}// End of main() Method}// End of class mainFrameTest