Why We Prefer Event Delegation Model And Its Component In GUI Programming. [Solved]

Question 1


Question 2

QUESTION 1: Describe the following concepts with syntax/example.

AWT components are few challenges such as look and feel, speed and memory. Is there any other alternative component available to handle these challenges? Also discuss how that components better then AWT components.

Why we prefer event delegation model and its component in GUI programming. Explain with appropriate examples.

What the use of wildcard and serialization? Justify the answer by adding an example against each.

Write the differences between class adapter and object adapter. Also define the importance of both concepts.  Write down the difference between byte stream and character stream.


Question 3

Write a program in a single class called DoubleLetters that does the following:

The program should read in a single line of text from the keyboard. It should then print to the console the same line of text with these changes: Letters should be doubled. Exclamation points (!) should be tripled. All other characters appear as they do in the input string.

The objectives of this assignment are to:

Be able to read text input from the keyboard using a Scanner object.

Be able to traverse the characters in a String using String class methods and a for loop.

Be able to use an if statement in a loop.


Answer to question 1

answer 1:

The Delegation Event model is one of the many techniques used to handle events in GUI (Graphical User Interface) programming languages. GUI represents a system where an user visually/graphically interacts with the system.

Event handling has three main components,
1· Events: An event is a change in state of an object.
2. Events Source: Event source is an object that generates an event.
3. Listeners: A listener is an object that listens to the event. A listener gets notified when an event occurs.


The goals of the event delegation model are as following:

1. It is easy to learn and implement
2. It supports a clean separation between application and GUI code.
3. It provides robust event handling program code which is less error-prone (strong compile-time checking)
4. It is Flexible, can enable different types of application models for event flow and propagation.
5. It enables run-time discovery of both the component-generated events as well as observable events.
6. It provides support for the backward binary compatibility with the previous model.

example of mouse event:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MouseTracker extends JFrame{
   private static final long serialVersionUID = 1L;
   private final JPanel trackPanel;
   private final JLabel statusLabel;

   public MouseTracker(){
      super(“Mouse Tracker”);
      trackPanel=new JPanel();
      trackPanel.setBackground(Color.BLUE);
      add(trackPanel, BorderLayout.CENTER);

      statusLabel=new JLabel(“”);
      add(statusLabel, BorderLayout.NORTH);

      trackPanel.addMouseListener(new MouseHandler());
      trackPanel.addMouseMotionListener(new MouseHandler());

   }

   private class MouseHandler implements MouseListener,
      MouseMotionListener{

      @Override
      public void mouseDragged(MouseEvent e) {
      // TODO Auto-generated method stub

   }

   @Override
      public void mouseMoved(MouseEvent e) {
         // TODO Auto-generated method stub

      }

      @Override
      public void mouseClicked(MouseEvent e) {
         statusLabel.setText(String
         .format(“Clicked at (x=%d, y=%d)”, e.getX(),
            e.getY()));
      }

      @Override
      public void mousePressed(MouseEvent e) {
         // TODO Auto-generated method stub

      }

      @Override
      public void mouseReleased(MouseEvent e) {
         // TODO Auto-generated method stub

      }

      @Override
      public void mouseEntered(MouseEvent e) {
         statusLabel.setText(“Mouse in scope”);

      }

      @Override
      public void mouseExited(MouseEvent e) {
         statusLabel.setText(“Mouse out of scope”);
      }

   }

   public static void main(String[] args){
      MouseTracker mt=new MouseTracker();
      mt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      mt.setSize(400,300);
      mt.setVisible(true)
   }
}

answer 2:

Wildcards in Java are basically the question marks which we use in generic programming, it basically represents the unknown type. We use Java Wildcard  widely in situations such as in a type of parameter, local variable, or field and also as a return type.

Types of wildcards:
1.Upper Bounded Wildcard: (? extends) If a variable is of in category, use extends keyword with wildcard.
example:
import java.util.Arrays;
import java.util.List;  
class WildcardDemo
{
    public static void main(String[] args)
    {
        //Upper Bounded Integer List
        List<Integer> list1= Arrays.asList(4,5,6,7);
        System.out.println(“Total sum is:”+sum(list1));
        List<Double> list2=Arrays.asList(4.1,5.1,6.1);
        System.out.print(“Total sum is:”+sum(list2));
    }
      private static double sum(List<? extends Number> list) 
    {
        double sum=0.0;
        for (Number i: list)
        {
            sum+=i.doubleValue();
        }
          return sum;
    }
}
2.Lower Bounded Wildcard: (? super) If a variable is of out category, use super keyword with wildcard.
example:
import java.util.Arrays;
import java.util.List;  
class WildcardDemo
{
    public static void main(String[] args)
    {
        //Lower Bounded Integer List
        List<Integer> list1= Arrays.asList(4,5,6,7);
        printOnlyIntegerClassorSuperClass(list1);
        List<Number> list2= Arrays.asList(4,5,6,7);
        printOnlyIntegerClassorSuperClass(list2);
    }
      public static void printOnlyIntegerClassorSuperClass(List<? super Integer> list)
    {
        System.out.println(list);
    }
}
3.Unbounded Wildcard:(?) If a variable can be accessed using Object class method then use an unbound wildcard.
example:
import java.util.Arrays;
import java.util.List;  
class unboundedwildcardemo
{
    public static void main(String[] args) 
    {  
        //Integer List
        List<Integer> list1= Arrays.asList(1,2,3);
        List<Double> list2=Arrays.asList(1.1,2.2,3.3);
        printlist(list1);
        printlist(list2);
    }  
    private static void printlist(List<?> list) 
    {  
        System.out.println(list);
    }
}

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
-It is mainly used to travel object’s state on the network (which is known as marshaling).

example:
import java.io.*;  
class Demo implements java.io.Serializable
{
    public int a;
    public String b;  
    // Default constructor
    public Demo(int a, String b)
    {
        this.a = a;
        this.b = b;
    }  
}
  class Test
{
    public static void main(String[] args)
    {   
        Demo object = new Demo(1, “geeksforgeeks”);
        String filename = “file.ser”;          
        // Serialization 
        try
        {   
            //Saving of object in a file
            FileOutputStream file = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(file);              
            // Method for serialization of object
            out.writeObject(object);              
            out.close();
            file.close();              
            System.out.println(“Object has been serialized”);  
        } 
        catch(IOException ex)
        {
            System.out.println(“IOException is caught”);
        }
    }
}


Answer to question 2

Swing is a graphical user interface gadget toolbox for Java. It is essential for oracle’s Java foundation classes – an API for giving GUI ( graphical user interface) for Java program.Swing was created to give a more complex arrangement of graphical user interface parts than the previous awt(abstract window toolkit). It has more remarkable and adaptable parts than awt. Swing gives a few progressed segments, eg. Selected board, scroll sheets, trees, tables and records. In contract to awt segments, swing parts are not executed by stage explicit code. All things considered, they are composed altogether in java in this manner are stage free.

Swing segments offer the accompanying preferences over AWT parts:

1. The conduct and presence of Swing segments is reliable across stages, though AWT segments will contrast from stage to stage.

2. Swing parts can be given their own “look and feel”.

3. Swing utilizes a more effective occasion model than AWT; subsequently, Swing parts can run more rapidly than their AWT partners.

Then again, Swing parts can take more time to stack than AWT segments.

Particle Applications should utilize either all AWT-based segments, or all Swing-based segments. Blending AWT and Swing segments in a similar application can cause issues with the stacking request of your segments.


Answer to question 3

Public class HelloWorld
{
public static void main(String[] args)
{
DoubleLetters dl = newDoubleLetters();
dl.DoDoubling();
}
}
DoubleLetters.java
import java.util.Scanner;
public class DoubleLetters
{

private final char SPECIAL_CHAR_EXCALAM =’!’;

public void DoDoubling()
{
Scanner in = newScanner(System.in);
String input =in.nextLine();
int length =input.length();
StringBuffer sb = newStringBuffer();
for (int i = 0; i <length; i++)
{
sb.append(input.charAt(i));
if(isAlphabet(input.charAt(i)))
{
sb.append(input.charAt(i));
}
if(input.charAt(i) == SPECIAL_CHAR_EXCALAM)
{
sb.append(input.charAt(i));
sb.append(input.charAt(i));
}
}
System.out.println(sb);
}

private boolean isAlphabet(char chr)
{
int asciiChar = chr;
return (asciiChar >= 65&& asciiChar <= 90) || (asciiChar >= 97 &&asciiChar <= 122);
}
}

Sample Output: {Code language=’java’ Hey!My car can’tmove!! HHeeyy!!!MMyy ccaarr ccaann’ttmmoovvee!!!!!!

Leave a Comment