Swing MouseMotion Adapter

Swing Mouse Motion Adapter

  1. MouseMotionAdapter class is an abstract adapter class in Java Swing.
  2. MouseMotionAdapter class is for receiving mouse motion events.
  3. Methods specified in MouseMotionAdapter class are empty.
  4. MouseMotionAdapter class exists as convenience for creating listener objects

Class declaration

Below is the declaration for java.awt.event.MouseMotionAdapter class –

public abstract class MouseMotionAdapter
   extends Object
      implements MouseMotionListener

Class constructors

MouseMotionAdapter()

Class methods

No.MethodReturn TypeParameterInvoked when
1mouseDragged()voidMouseEventMouse button is pressed on a component and then dragged.
2mouseMoved()voidMouseEventMouse cursor has been moved onto a component but no buttons is clicked

Methods inherited

This class inherits methods from the following classes:

java.lang.Object

WindowAdapter Example

AdapterExample.java

package com.c4learn;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class AdapterExample {
   private JFrame baseFrame;
   private JLabel headLabel;
   private JLabel msgLabel;
   private JPanel controlPanel;

   public AdapterExample() {
      initializeUI();
   }

   public static void main(String[] args) {
      AdapterExample adapterDemo = new AdapterExample();
      adapterDemo.showMouseApapter();
   }

   private void initializeUI() {
      baseFrame = new JFrame("Java Swing Examples");
      baseFrame.setSize(500, 500);
      baseFrame.setLayout(new GridLayout(3, 1));

      headLabel = new JLabel("", JLabel.CENTER);
      msgLabel = new JLabel("", JLabel.CENTER);

      msgLabel.setSize(300, 100);

      baseFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent) {
            System.exit(0);
         }
      });

      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      baseFrame.add(headLabel);
      baseFrame.add(controlPanel);
      baseFrame.add(msgLabel);
      baseFrame.setVisible(true);
   }

   private void showMouseApapter() {
      headLabel.setText("MouseMotionAdapter Example");

      JPanel panel = new JPanel();
      panel.setBackground(Color.gray);
      panel.setLayout(new FlowLayout());
      
      panel.addMouseMotionListener(new MouseMotionAdapter() {
         public void mouseMoved(MouseEvent e) {
            msgLabel.setText("Mouse Moved: (" + e.getX() + ", "
                  + e.getY() + ")");
         }
      });

      JLabel msglabel = new JLabel("www.c4learn.com");
      panel.add(msglabel);

      controlPanel.add(panel);
      baseFrame.setVisible(true);
   }
}

After running program in the eclipse you will see below output

mouse_motion_adapter

Swing Window Adapter

Swing Window Adapter

  1. WindowAdapter class is an abstract adapter class in Java Swing.
  2. WindowAdapter class is for receiving window events.
  3. Methods specified in WindowAdapter class are empty.
  4. WindowAdapter class exists as convenience for creating listener objects

Class declaration

Below is the declaration for java.awt.event.WindowAdapter class –

public abstract class WindowAdapter
   extends Object
      implements WindowListener, 
                 WindowStateListener, 
                 WindowFocusListener

Class constructors

WindowAdapter()

Class methods

No.MethodReturn TypeParameterInvoked when
1windowActivated()voidWindowEventwindow is activated.
2windowClosed()voidWindowEventwindow has been closed.
3windowClosing()voidWindowEventwindow is in the process of being closed.
4windowDeactivated()voidWindowEventwindow is de-activated.
5windowDeiconified()voidWindowEventwindow is de-iconified.
6windowGainedFocus()voidWindowEventWindow is set to be the focused Window
7windowIconified()voidWindowEventwindow is iconified.
8windowLostFocus()voidWindowEventWindow is no longer the focused Window
9windowOpened()voidWindowEventwindow has been opened.
10windowStateChanged()voidWindowEventwindow state is changed.

Methods inherited

This class inherits methods from the following classes:

java.lang.Object

WindowAdapter Example

AdapterExample.java

package com.c4learn;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class AdapterExample {
   private JFrame baseFrame;
   private JLabel headLabel;
   private JLabel msgLabel;
   private JPanel controlPanel;

   public AdapterExample() {
      initializeUI();
   }

   public static void main(String[] args) {
      AdapterExample adapterDemo = new AdapterExample();
      adapterDemo.showWindowApapter();
   }

   private void initializeUI() {
      baseFrame = new JFrame("Java Swing Examples");
      baseFrame.setSize(500, 500);
      baseFrame.setLayout(new GridLayout(3, 1));

      headLabel = new JLabel("", JLabel.CENTER);
      msgLabel = new JLabel("", JLabel.CENTER);

      msgLabel.setSize(300, 100);
      
      baseFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent) {
            System.exit(0);
         }
      });
      
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      baseFrame.add(headLabel);
      baseFrame.add(controlPanel);
      baseFrame.add(msgLabel);
      baseFrame.setVisible(true);
   }

   private void showWindowApapter() {
      headLabel.setText("WindowAdapter Example");

      final JFrame innerFrame = new JFrame();
      innerFrame.setSize(300, 200);
      innerFrame.setTitle("WindowAdapter Demo");
      
      innerFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent) {
            innerFrame.dispose();
         }
      });
      
      JLabel msglabel = new JLabel("Welcome to Swing", JLabel.CENTER);
      innerFrame.add(msglabel);
      innerFrame.setVisible(true);
   }
}

After ruuning program in the eclipse you will see below output

window_adapter

JSP Deleting cookies

We have already learnt about the basic concepts of the cookies and the way to set cookies and accessing the cookies. In this tutorial we will be learning, how to remove or delete the already created cookies ?

JSP Deleting cookies

<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
   <h1>Reading Cookies</h1>
   <%
      Cookie cookie = null;
      Cookie[] cookies = null;

      cookies = request.getCookies();
      if (cookies != null) {
         out.println("<h2>List of Cookies :</h2>");
		 
         for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            
            out.print("Deleted cookie: " + cookie.getName());
            out.print("Name : " + cookie.getName());
            out.print("Value: " + cookie.getValue());
         }
      } else {
         out.println("<h2>No cookies founds</h2>");
      }
   %>
</body>
</html>

Output of the program :
deleting cookies in jsp

Explanation : JSP Deleting cookies

In the above example, We have deleted the cookies that has been already created by executing some JSP program. Now we also know the way to access those cookies using the getCookies() method.

Steps to delete the cookies :

In order to delete the cookies we need to execute following steps –

  1. Access the existing cookie
  2. Change the Maximum age of the cookie to zero
  3. Update the cookie object

Below 3 lines are doing exactly same work as mentioned in the above 3 steps –

cookie = cookies[i];        // Step 1
cookie.setMaxAge(0);        // Step 2
response.addCookie(cookie); // Step 3

JSP Accessing Cookies : Read cookies in JSP

In the previous chapter we have learnt the way to set cookies using JSP. In this example we will be learning how to access the cookies using the JSP. Below tutorial will show us detail explanation about the JSP accessing cookies.

JSP Accessing Cookies :

Consider the below program –

<html>
<head>
<title>Accessing and Reading Cookies</title>
</head>
<body>
   <%
      Cookie cookie = null;
      Cookie[] cookies = null;

      cookies = request.getCookies();
      if (cookies != null) {
         out.println("<h2> List of cookies : </h2>");
         for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            out.print("Name : " + cookie.getName() + ",  ");
            out.print("Value: " + cookie.getValue() + " <br/>");
         }
      } else {
         out.println("<h2>No cookies founds</h2>");
      }
   %>
</body>
</html>

Output of the Program :
reading accessing the cookies with JSP

Explanation : JSP Accessing Cookies

The above program we are accessing the cookies that are already present or valid. We need the cookie object to get the details of the cookies.

Cookie cookie = null;
Cookie[] cookies = null;

We have created the array of the cookie objects. JSP provides the way to access the cookies using the getCookies( ) method of HttpServletRequest.

cookies = request.getCookies();

Using the above line we can get all the cookies in an array. Now we can access the elements of the array using the loop to print the details of each cookie –

for (int i = 0; i < cookies.length; i++) {
   cookie = cookies[i];
   out.print("Name : " + cookie.getName());
   out.print("Value: " + cookie.getValue());
}

Now in order to print the details of each cookie we need to get individual cookie object from the array.

MethodExplanation
cookie.getName()Used to print the name of the cookie
cookie.getValue()Used to print the value of the cookie

JSP Setting cookies

In the previous chapter we have learnt the basic concepts of the cookies. In this chapter we will be learning how to set the cookies in JSP.

JSP Setting cookies

In order to demonstrate the cooking setting example consider the following index.html page –

<html>
<body>
   <form action="main.jsp" method="GET">
      <table>
         <tr>
            <td>Name</td>
            <td><input type="text" name="fname"></td>
         </tr>
         <tr>
            <td>City</td>
            <td><input type="text" name="city" /></td>
         </tr>
         <tr>
            <td>Pin</td>
            <td><input type="text" name="pin" /> &nbsp; 
                 <input type="submit" value="Submit" /></td>
         </tr>
      </table>
   </form>
</body>
</html>

Following screen will be created when we run above page on server –

form in jsp
Action mentioned in the above form is main.jsp

<form action="main.jsp" method="GET">

Below is the content of the main.jsp file.

<%
   // Creating the cookies object      
   Cookie fname = new Cookie("fname", request.getParameter("fname"));
   Cookie city = new Cookie("city", request.getParameter("city"));
   Cookie pin = new Cookie("pin", request.getParameter("pin"));

   // Setting expiry date of cookies = 24 Hr
   fname.setMaxAge(60 * 60 * 24);
   city.setMaxAge(60 * 60 * 24);
   pin.setMaxAge(60 * 60 * 24);

   // Adding cookies to the response header.
   response.addCookie(fname);
   response.addCookie(city);
   response.addCookie(pin);
%>

<html>
<head>
<title>JSP Setting Cookies</title>
</head>
<body>
   <h1>Values stored in cookies -</h1>
   <table>
      <tr>
         <td>Name</td>
         <td><%=request.getParameter("fname")%></td>
      </tr>
      <tr>
         <td>City</td>
         <td><%=request.getParameter("city")%></td>
      </tr>
      <tr>
         <td>Pin</td>
         <td><%=request.getParameter("pin")%></td>
      </tr>
   </table>
</body>
</html>

Steps for Setting cookies in JSP

There are following 3 steps involved for Setting cookies in JSP –

  1. Creating the cookies object
  2. Setting expiry date of cookies
  3. Adding cookies to the response header

Consider all the steps one by one –

Step 1 : Creating the cookies object

For Setting cookies in JSP we need to create the cookies in the JSP. Syntax for creating the cookie object is as follow –

Cookie cookie = new Cookie("key","value");

We need to pass Cookies name and cookie value as parameter to the Cookie constructor. Parameters passed to the constructor are of type string.

Following are some of the illegal characters which cannot be used for creating the cookie name –

  1. [ ]
  2. ( )
  3. = ,
  4. ” /
  5. ? @
  6. : ;

Step 2 : Setting expiry date of cookies

In this step we need to set the maximum age of the cookie after which cookies will be destroyed automatically. Below is the syntax to set maximum age of the cookie in JSP –

cookie.setMaxAge(int seconds)

below is the code snippet from the above example where we have set maximum age of the cookies to 25 hours.

fname.setMaxAge(60 * 60 * 24);
city.setMaxAge(60 * 60 * 24);
pin.setMaxAge(60 * 60 * 24);

Consider the above example –

setMaxAge() function is used for setting the maximum age of the cookie. Parameter passed to the setMaxAge() method is value in seconds for which cookies will be considered to be valid

Step 3 : Adding cookies to response header

In this step we add the cookie objects to the HTTP response header. Below is the syntax to add the cookies to the response header –

response.addCookie(cookie);

JSTL XML choose tag

The <x:choose> works like a Java switch statement in that it lets you choose between a number of alternatives. Where the switch statement has case statements, the <x:choose> tag has <x:when> tags. A a switch statement has default clause to specify a default action and similar way <x:choose> has <x:otherwise> as default clause.

Attribute:

  • The <x:choose> tag does not have any attribute.

  • The <x:when> tag has one attributes which is listed below.

  • The <x:otherwise> tag does not have any attribute.

The <x:when> tag has following attributes:

AttributeDescriptionRequiredDefault
selectCondition to evaluateYesNone

Example:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

<html>
<head>
  <title>JSTL XML Tags</title>
</head>
<body>

<c:set var="xmlData">
  <Animals>
    <Animal>
      <name>Tiger</name>
      <type>Non-Veg</type>
    </Animal>
    <Animal>
      <name>Rabbit</name>
      <type>Veg</type>
    </Animal>
  </Animals>
</c:set>

<x:parse xml="${xmlData}" var="xml"/>
<x:choose>
   <x:when select="$xml//Animal/name = 'Tiger'">
      We found Tiger
   </x:when>
   <x:when select="$xml//Animal/name = 'Rabbit'">
      We found Rabbit
   </x:when>
   <x:otherwise>
      Empty Cart
   </x:otherwise>
</x:choose>

</body>
</html>

Output :

We found Tiger 

JSTL Core tag – url() : Function

JSTL Core tag – url() : Function

  1. The <c:url> tag is used to format a URL into a string and stores it into a variable.
  2. Tag can perform automatic rewriting of URL when necessary.
  3. The var attribute specifies the variable that will contain the formatted URL.
  4. The JSTL url tag is just an alternative method of writing the call to the response.encodeURL() method.
  5. The only real advantage the url tag provides is proper URL encoding, including any parameters specified by children param tag.

Attribute:

The <c:url> tag has following attributes:

AttributeDescriptionRequiredDefault
valueBase URLYesNone
context/ followed by the name of a local web applicationNoCurrent application
varName of the variable to expose the processed URLNoPrint to page
scopeScope of the variable to expose the processed URLNoPage

JSTL Example :

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>JSTL Tag Example</title>
</head>
<body>

<a href="<c:url value="http://www.google.com"/>">Testing Google</a>

</body>
</html>

Output :

Testing Google

JSTL Core tag – redirect() : Function

The <c:redirect> tag redirects the browser to an alternate URL by providing automatically URL rewriting, it supports context-relative URLs, and it supports the <c:param> tag.

Attribute:

The <c:redirect> tag has following attributes:

AttributeDescriptionRequiredDefault
urlURL to redirect the user’s browser toYesNone
context/ followed by the name of a local web applicationNoCurrent application

JSTL Example :

If you need to pass parameters to a <c:import> tag, use the <c:url> tag to create the URL first as shown below:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>JSTL Tag Example</title>
</head>
<body>

<c:redirect url="http://www.c4learn.com"/>

</body>
</html>

Above example would redirect request to http://www.c4learn.com

JSTL Core tag – param() : Function

The <c:param> tag allows proper URL request parameter to be specified with URL and it does any necessary URL encoding required.

Within a <c:param> tag, the name attribute indicates the parameter name, and the value attribute indicates the parameter value:

Attribute:

The <c:param> tag has following attributes:

AttributeDescriptionRequiredDefault
nameName of the request parameter to set in the URLYesNone
valueValue of the request parameter to set in the URLNoBody

JSTL Example :

If you need to pass parameters to a <c:import> tag, use the <c:url> tag to create the URL first as shown below:

index.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>JSTL Tag Example</title>
</head>
<body>

<c:url value="output.jsp" var="generatedURL">
   <c:param name="name" value="Programming Tutorials"/>
   <c:param name="url" value="www.c4learn.com"/>
</c:url>

<c:import url="${generatedURL}"/>

</body>
</html>

output.jsp

Website Name : <%= request.getParameter("name")%><br />
URL : <%= request.getParameter("url")%>

Output :

It would call following url –

"output.jsp?trackingId=1234;reportType=summary"

Output produced on the output.jsp will be –

Website Name : Programming Tutorials
URL : www.c4learn.com 

JSTL Core tag – foreach() : Function

These tags exist as a good alternative to embedding a Java for, while, or do-while loop via a scriptlet. The <c:forEach> tag is the more commonly used tag because it iterates over a collection of objects. The <c:forTokens> tag is used to break a string into tokens and iterate through each of the tokens.

Attribute:

The <c:forEach> tag has following attributes:

AttributeDescriptionRequiredDefault
itemsInformation to loop overNoNone
beginElement to start with (0 = first item, 1 = second item, …)No0
endElement to end with (0 = first item, 1 = second item, …)NoLast element
stepProcess every step itemsNo1
varName of the variable to expose the current itemNoNone
varStatusName of the variable to expose the loop statusNoNone

The <c:forTokens> tag has similar attributes as <c:forEach> except one additional attribute delims which specifies sharacters to use as delimiters.

AttributeDescriptionRequiredDefault
delimsCharacters to use as delimitersYesNone

Example for <c:forEach>:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>JSTL Tag Example</title>
</head>
<body>

<c:forEach var="i" begin="1" end="5">
   Value of i : <c:out value="${i}"/><p>
</c:forEach>

</body>
</html>

Output :

Value of i : 1
Value of i : 2
Value of i : 3
Value of i : 4
Value of i : 5

Example for <c:forTokens>:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>JSTL Tag Example</title>
</head>
<body>

<c:forTokens items="A,B,C,D,E" delims="," var="name">
   <c:out value="${name}"/><p>
</c:forTokens>

</body>
</html>

Output :

A
B
C
D
E