Consider a simple GUI based Java program as shown in screenshot and code given below:


Example:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class TestSwingCommonFeatures extends JFrame {
  public TestSwingCommonFeatures() {
    // Create a panel to group three buttons
    JPanel 	p1 = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 2));
    Jbutton	 jbtLeft = new JButton("Left");
    JButton 	jbtCenter = new JButton("Center");
    JButton 	jbtRight = new JButton("Right");
    jbtLeft.setBackground(Color.WHITE);
    jbtCenter.setForeground(Color.GREEN);
    jbtRight.setToolTipText("This is the Right button");
    p1.add(jbtLeft);
    p1.add(jbtCenter);
    p1.add(jbtRight);
    p1.setBorder(new TitledBorder("Three Buttons"));
    // Create a font and a line border
    Font largeFont = new Font("TimesRoman", Font.BOLD, 20);
    Border lineBorder = new LineBorder(Color.BLACK, 2);
    // Create a panel to group two labels
    JPanel p2 = new JPanel(new GridLayout(1, 2, 5, 5));
    JLabel jlblRed = new JLabel("Red");
    JLabel jlblOrange = new JLabel("Orange");
    jlblRed.setForeground(Color.RED);
    jlblOrange.setForeground(Color.ORANGE);
    jlblRed.setFont(largeFont);
    jlblOrange.setFont(largeFont);
    jlblRed.setBorder(lineBorder);
    jlblOrange.setBorder(lineBorder);
    p2.add(jlblRed);
    p2.add(jlblOrange);
    p2.setBorder(new TitledBorder("Two Labels"));
    // Add two panels to the frame
    setLayout(new GridLayout(2, 1, 5, 5));
    add(p1);
    add(p2);
  }
// rest of the code
}

A window based program is called event driven program. The signals that a program receives from the OS as a result of your actions are called events. Unlike the old rigid old sequential programs, it puts user in charge, user control the sequence of program. Application waits for the user action. This approach is called event driven programming.

Event Delegation Model

The Delegation Event Model used by Java to handle user interaction with GUI components. It describes how your program can respond to user interaction. It has three important players.

  • Event Source
  • Event Listener/Handler
  • Event Object

Event Source

  • GUI component that generates the event.
  • Eexample: button

Event Listener/Handler

  • It receives and handles events. It contains business logic
  • Example: displaying information useful to the user, computing a value

Event Object

  • It is created when an event occurs (i.e., user interacts with a GUI component). It contains all necessary information. It is represented by an Event class.
  • Example: GUI Program

Event Basics

All Events are objects of Event Classes. All Event Classes derive from EventObject. When an Event occurs, Java sends a message to all registered Event Listeners from the Event source. The EventObject class is found in the java.util package. The AWTEvent class. An immediate subclass of EventObject. Defined in java.awt package. Root of all AWT-based events.

3 Steps for event Handler

  1. Either implements a listener interface or extends a class that implements a listener interface
  2. Register your listener
     someComponent.addActionListener(instanceOfMyClass);
  1. Implement user action
     public void actionPerformed(ActionEvent e) 
     { ...//code that reacts to the action... }

Example:

public class TryWindow extends JFrame implements ActionListener{
static JTextField  tf=new JTextField("     no     ");
static int count=0;

    public void actionPerformed(ActionEvent e){
	count++;
    tf.setText("hiiii  "+count);    }
Public static void main(String arg[]){
	JButton b = new JButton("one");
	TryWindow frame=new TryWindow();
	b.addActionListener(frame);
       panel1.setLayout(new FlowLayout());
       panel1.add(b);
       panel1.add(tf);
	//other code for frame
}

Event Class Listener Interface Listener Methods
ItemEvent ItemListener itemStateChanged()
KeyEvent KeyListener keyPressed() , keyReleased(),keyTyped()
MouseEvent MouseListener, MouseMotionListener mouseClicked() , mouseEntered(), mouseExited(), mousePressed(),mouseReleased()mouseDragged(),mouseMoved()
TextEvent TextListener textValueChanged()
WindowEvent WindowListener windowActivated(), windowClosed(), windowClosing(),windowDeactivated(), windowDeiconified(),windowIconified(), windowOpened()

Mouse Listener Example

import java.awt.*;
import java.awt.event.*;
public class MouseDemo extends Frame
                     implements MouseListener, MouseMotionListener
{
     TextField tf;
     public MouseDemo(String title){
		super(title);
		tf = new TextField(60);
		 addMouseListener(this);	 // Register event listener to the event source
	}
	public void launchFrame() {
 		add(tf, BorderLayout.SOUTH); // Add components to the frame
		setSize(300,300);
		setVisible(true);
	}
public void mouseClicked(MouseEvent me) {
 String msg = "Mouse clicked.";
 tf.setText(msg);
}
public void mouseEntered(MouseEvent me) {
String msg = "Mouse entered component.";
 tf.setText(msg);
}
public void mouseExited(MouseEvent me) {
String msg = "Mouse exited component.";
 tf.setText(msg);
}
public void mousePressed(MouseEvent me) {
	 String msg = "Mouse pressed.";
	 tf.setText(msg);
}
public void mouseReleased(MouseEvent me) {
	 String msg = "Mouse released.";
	 tf.setText(msg);   }
 public void mouseDragged(MouseEvent me) {
	 String msg = "Mouse dragged at " + me.getX()	 + "," + me.getY();
	tf.setText(msg);}
public void mouseMoved(MouseEvent me) {
 String msg = "Mouse moved at " + me.getX() + "," + me.getY();
 tf.setText(msg);}
public static void main(String args[]) {
	MouseDemo med =new MouseDemo("Mouse Events Demo");
	 med.launchFrame();
}}

Window Listener Example

import java.awt.*;
 import java.awt.event.*;
class CloseFrame extends Frame implements WindowListener {

 CloseFrame(String title) {
	 super(title);
	this.addWindowListener(this);
	}
void launchFrame() {
	setSize(300,300);
	setVisible(true);
}
//Implement methods of listener interface
public void windowActivated(WindowEvent e) {
System.out.println(“Window is activated”);
}
public void windowClosed(WindowEvent e) {}
public void windowClosing(WindowEvent e) {
	setVisible(false);
	System.exit(0);
}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {
System.out.println(“Window is Deiconified”);
}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public static void main(String args[ ]) {
 CloseFrame cf = new CloseFrame("Close Window Example");
 cf.launchFrame();
}}

Adapter Classes (Alternate for EventListener)

Often we only really want to implement one or two of the event handlers. But interface implementation requires us to implement all of them. Java adapter classes allow us to solve this problem. Implement the event-handling interfaces in a trivial way, just to satisfy the interface. We extend the class and override the methods that we need. Some adapter classes are:

  • KeyAdapter (instead of KeyListener)
  • WindowAdapter
  • MouseAdapter (MouseListener)
  • MouseMotionAdapter (MouseMotionListener) etc…

Example:

import java.awt.*; import java.awt.event.*;
 class CloseFrame extends Frame{
 Label label;
 CFListener w = new CFListener(this);
 CloseFrame(String title) {
 	super(title);
	label = new Label("Close the frame.");
	 this.addWindowListener(w); }
void launchFrame() {
setSize(300,300);
setVisible(true); }
 public static void main(String args[]) {
 CloseFrame cf = new CloseFrame("Close Window Example");
 cf.launchFrame();
}
class CFListener extends WindowAdapter {
	 CloseFrame ref;
	 CFListener( CloseFrame ref ){
		 this.ref = ref;
	}

	public void windowClosing(WindowEvent e) {
		ref.dispose();
		System.exit(1);
	}
}

Inner Classes

Class declared within another class is called Inner class. Why use inner classes? It helps simplify your programs especially in event handling. Consider following example.

Example:

import java.awt.*; import java.awt.event.*;
 class CloseFrame extends Frame{
 Label label;
	 CloseFrame(String title) {
		 super(title);
		 label = new Label("Close the frame.");
		 this.addWindowListener(new CFListener()); }
	void launchFrame() {
		 setSize(300,300);
		 setVisible(true);	}
   class CFListener extends WindowAdapter {
 		public void windowClosing(WindowEvent e) {
			 dispose();
			 System.exit(1);	 } }

	public static void main(String args[]) {
		CloseFrame cf = new CloseFrame("Close Window Example");
		 cf.launchFrame();
	}
}

Anonymous Inner Class

Unnamed inner classes are called Anonymous Inner classes. Why use anonymous inner classes? It further simplify your codes especially in event handling. Consider the following example.

Example:

import java.awt.*; import java.awt.event.*;
class CloseFrame extends Frame{
Label label;
	CloseFrame(String title) {
		super(title);
		label = new Label("Close the frame.");
		this.addWindowListener(
			          	new WindowAdapter() {
				public void windowClosing(WindowEvent e){
				dispose();
				System.exit(1);
			}
		}
		)
}\\end of constructor
	void launchFrame() {
		 setSize(300,300);
		 setVisible(true);
	}
	public static void main(String args[]) {
	CloseFrame cf = new CloseFrame("Close Window Example");
	 cf.launchFrame();
	}
}

You can implement your listeners inside the class that extends your JFrame, making it an inner class. This enables you to put everything in one class (and hence file). Inner classes have access to the private data of the outer class.

Example:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
  // An action listener that prints a message.

public class ClickListener implements ActionListener
 {
    public void actionPerformed(ActionEvent event)
   {
      System.out.println("I was clicked.");
   }
}
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
//   This program demonstrates how to install an action listener.

public class ButtonTester {

    public static void main(String[] args)  {
      JFrame frame = new JFrame();
      JButton button = new JButton("Click me!");

      frame.add(button);
:     ActionListener listener = new ClickListener();
      button.addActionListener(listener);

      frame.setSize(100, 60);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
    }}

Event Handling JCheckbox

private class MyCheckBoxHandler implements ItemListener {
………..
private JCheckBox italic;
italic = new JCheckBox( "Italic" );
container.add( italic );
// register listeners for JCheckBoxes
CheckBoxHandler handler = new CheckBoxHandler();
italic.addItemListener( handler );
………….
public void itemStateChanged( ItemEvent event )
          {  // process bold checkbox events
             if ( event.getSource() == italic){…..}
	     }
………….
}

Related Posts

Tagged with: JAVAJAVA GUIObject Oriented
 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds