Home > Articles > Home & Office Computing > eBay/Yahoo/Google

This chapter is from the book

Implementation of the Drag-and-Drop Application

Listing 6.2 shows the drag-and-drop application's class.

Listing 6.2. com.gwtsolutions.client.DragAndDrop

20.package com.gwtsolutions.client;
21.
22.import com.google.gwt.core.client.EntryPoint;
23.import com.google.gwt.core.client.GWT;
24.import com.google.gwt.user.client.ui.AbsolutePanel;
25.import com.google.gwt.user.client.ui.RootPanel;
26.
27.public class DragAndDrop implements EntryPoint {
28.  public void onModuleLoad() {
29.    DragAndDropConstants constants =
30.        (DragAndDropConstants) GWT
31.            .create(DragAndDropConstants.class);
32.
33.    final AbsolutePanel ap = new AbsolutePanel();
34.
35.    ap.add(new IpodDropTarget(new ShoppingCartPanel(constants
36.        .iPodsOnly())), 125, 10);
37.
38.    ap.add(new ZuneDropTarget(new ShoppingCartPanel(constants
39.        .zunesOnly())), 125, 260);
40.
41.    final MusicPlayer blackIpod =
42.        new MusicPlayer("images/ipod-nano-black.jpg",
43.            constants.blackIPodInfo());
44.
45.    final MusicPlayer blackZune =
46.        new MusicPlayer("images/zune-black.jpg", constants
47.            .blackZuneInfo());
48.
49.    final MusicPlayer silverIpod =
50.        new MusicPlayer("images/ipod-nano-silver.jpg",
51.            constants.silverIPodInfo());
52.
53.    final MusicPlayer brownZune =
54.        new MusicPlayer("images/zune-brown.jpg", constants
55.            .brownZuneInfo());
56.
57.    ap.add(new MusicPlayerDragSource(blackIpod), 10, 20);
58.    ap.add(new MusicPlayerDragSource(brownZune), 10, 120);
59.    ap.add(new MusicPlayerDragSource(silverIpod), 10, 200);
60.    ap.add(new MusicPlayerDragSource(blackZune), 10, 300);
61.
62.    ap.addStyleName("dragPanel");
63.    RootPanel.get().add(ap);
64.  }
65.}

The preceding code is straightforward. We create an absolute panel, to which we add two shopping cart panels, each wrapped in a drop target. Then we create four music players and add each of them, wrapped in music player drag sources, to the absolute panel. After that flurry of activity, we have an absolute panel with four drag sources and two drop targets. Finally, we attach a CSS style to the absolute panel and add it to the root panel of the page.

The MusicPlayer and ShoppingCartPanel classes are GWT composite widgets. Let's look at their implementations before we dive into the dnd module.

Using the Music Player and Shopping Cart Panel Components

The MusicPlayer class is listed in Listing 6.3.

Listing 6.3. com.gwtsolutions.client.MusicPlayer

1.package com.gwtsolutions.client;
2.
3.import com.google.gwt.user.client.ui.Composite;
4.import com.google.gwt.user.client.ui.Image;
5.
6.public class MusicPlayer extends Composite {
7.  private Image image;
8.  private String info;
9.
10.  public MusicPlayer(String imageUrl, String info) {
11.    image = new Image(imageUrl);
12.    this.info = info;
13.    initWidget(image);
14.  }
15.
16.  public String getInfo() {
17.    return info;
18.  }
19.}

This is about as simple as a composite widget gets. The music player composite contains an image and some information about the player. Notice the call to the Composite class's initWidget method. As with all composite widgets that extend Composite, you must call that method in the constructor.

The shopping cart panel composite is listed in Listing 6.4.

Listing 6.4. com.gwtsolutions.client.ShoppingCartPanel

1.package com.gwtsolutions.client;
2.
3.import com.google.gwt.user.client.ui.Composite;
4.import com.google.gwt.user.client.ui.HorizontalPanel;
5.import com.google.gwt.user.client.ui.Image;
6.import com.google.gwt.user.client.ui.Label;
7.import com.google.gwt.user.client.ui.VerticalPanel;
8.
9.public class ShoppingCartPanel extends Composite {
10.  private final HorizontalPanel hp = new HorizontalPanel();
11.  private final VerticalPanel vp = new VerticalPanel();
12.
13.  public ShoppingCartPanel(String title) {
14.    initWidget(hp);
15.    hp.add(new Image("images/shopping_cart.gif"));
16.    hp.addStyleName("cartPanel");
17.    vp.add(new Label(title));
18.    hp.add(vp);
19.  }
20.
21.  public void add(MusicPlayer ipod) {
22.    vp.add(new Label(ipod.getInfo()));
23.  }
24.}

This composite contains a horizontal panel that in turn contains the shopping cart image and a vertical panel. The vertical panel initially contains only a title. When a music player is dropped on a drop target, the drop target invokes ShoppingCartPanel.add() to add the music player to the cart. That add method simply adds the music player's information, in the form of a GWT label, to the vertical panel.

Using Drag Sources and Drop Targets

We've seen the application and its two composite widgets. Now things start to get interesting because next we look at how you implement your own drag sources and drop targets by using the drag-and-drop module.

Our sample application implements a single drag source—the MusicPlayerDragSource class—and two drop targets: IpodDropTarget and ZuneDropTarget. Let's start with the drag source, which is listed in Listing 6.5.

Listing 6.5. com.gwtsolutions.client.MusicPlayerDragSource

1.package com.gwtsolutions.client;
2.
3.import com.gwtsolutions.components.client.ui.dnd.DragSource;
4.import com.gwtsolutions.components.client.ui.dnd.DropTarget;
5.
6.public class MusicPlayerDragSource extends DragSource {
7.  public MusicPlayerDragSource(MusicPlayer musicPlayer) {
8.    super(musicPlayer);
9.  }
10.
11.  public void dragStarted() {
12.    addStyleName("pointerCursor");
13.  }
14.
15.  public void droppedOutsideDropTarget() {
16.    super.droppedOutsideDropTarget();
17.    removeStyleName("pointerCursor");
18.  }
19.
20.  public void acceptedByDropTarget(DropTarget dt) {
21.    removeStyleName("pointerCursor");
22.  }
23.
24.  public void rejectedByDropTarget(DropTarget dt) {
25.    super.rejectedByDropTarget(dt);
26.    removeStyleName("pointerCursor");
27.  }
28.}

This class extends the DragSource class, which is part of our dnd module. That DragSource class implements four methods that subclasses are likely to override:

  • void dragStarted()
  • void droppedOutsideDropTarget()
  • void acceptedByDropTarget(DropTarget dt)
  • void rejectedByDropTarget(DropTarget dt)

The preceding methods are called by the dnd module when one of the following occurs: The drag starts; the drag source is dropped outside a drop target; or the drop is accepted or rejected by a drop target.

When the drag starts, the music player drag source adds to itself the CSS style named pointerCursor. That style defines a single property, the cursor property, with the value pointer. Setting that style effectively changes the cursor when it's over our drag source. See Listing 6.9 on page 181 for the definition of that CSS style.

When a music player drag source is dropped outside any drop target, we invoke super.droppedOutsideDropTarget(), which returns the drag source to its original position, and we reset the cursor by removing the pointerCursor style from the drag source widget.

When a music player drag source is dropped on a drop target that rejects the drop, we invoke super.droppedOutsideDropTarget(), which returns the drag source to its original position and resets the cursor. Notice that in this case, dropping a music player outside a drop target has the same effect, from the point of view of the drag source, as being rejected by a drop target.

When a music player drag source is dropped on a drop target that accepts the drop, we simply reset the cursor. It's up to the drop target to add the music player to the drop target's enclosed panel.

We only have one drag source class, because iPods and Zunes react identically when they are dragged and dropped; however, we need two drop targets because the iPod drop target only accepts iPods and the Zune drop target only accepts Zunes. That said, however, the two kinds of drop targets are much more similar than they are different, so we have a base class that encapsulates those similarities. That drop target base class is listed in Listing 6.6.

Listing 6.6. com.gwtsolutions.client.MusicPlayerDropTarget

1.package com.gwtsolutions.client;
2.
3.import com.google.gwt.user.client.ui.AbsolutePanel;
4.import com.google.gwt.user.client.ui.Widget;
5.import com.gwtsolutions.components.client.ui.dnd.DragSource;
6.import com.gwtsolutions.components.client.ui.dnd.DropTarget;
7.
8.public abstract class MusicPlayerDropTarget extends DropTarget {
9.  public MusicPlayerDropTarget(Widget w) {
10.    super(w);
11.  }
12.
13.  public void dragSourceEntered(DragSource ds) {
14.    if (acceptsDragSource(ds)) {
15.      ds.addStyleName("moveCursor");
16.      addStyleName("moveCursor");
17.      addStyleName("blueBorder");
18.    }
19.    else {
20.      ds.addStyleName("noDropCursor");
21.      addStyleName("noDropCursor");
22.    }
23.  }
24.
25.  public void dragSourceExited(DragSource ds) {
26.    if (acceptsDragSource(ds)) {
27.      ds.removeStyleName("moveCursor");
28.      removeStyleName("moveCursor");
29.      removeStyleName("blueBorder");
30.    }
31.    else {
32.      ds.removeStyleName("noDropCursor");
33.      removeStyleName("noDropCursor");
34.    }
35.  }
36.
37.  public void dragSourceDropped(DragSource ds) {
38.    super.dragSourceDropped(ds);
39.
40.    if (acceptsDragSource(ds)) {
41.      ((ShoppingCartPanel) getWidget()).add((MusicPlayer) ds
42.          .getWidget());
43.
44.      ((AbsolutePanel) ds.getParent()).remove(ds);
45.
46.      removeStyleName("moveCursor");
47.      removeStyleName("blueBorder");
48.    }
49.    else {
50.      ds.removeStyleName("noDropCursor");
51.      removeStyleName("noDropCursor");
52.    }
53.  }
54.}

This class extends the DropTarget class, which is also part of our dnd module. That class implements three methods that subclasses typically override:

  • void dragSourceEntered(DragSource ds)
  • void dragSourceDropped(DragSource ds)
  • void dragSourceExited(DragSource ds)

The preceding methods are called by the dnd module when a drag source enters, exits, or is dropped on a drop target. The drop target superclass also defines one abstract method that subclasses must implement: boolean acceptsDragSource(DragSource ds), which determines whether a drop target will accept a given drag source.

When a music player drag source enters or exits a drop target, we manipulate styles depending on whether the drag source is acceptable to the drop target to achieve drag-over and drag-under effects.

When a music player drag source is dropped on the drop target, we call super.dragSourceDropped(), which notifies the drag source of the drop by calling the drag source's acceptedByDropTarget method or rejectedByDropTarget method, depending on whether or not the drop target accepts the drop.

Now that we've encapsulated common drop target behavior in a base class, let's look at the subclasses specific to iPods and Zunes, listed in Listing 6.7 and Listing 6.8.

Listing 6.7. com.gwtsolutions.public.IpodDropTarget

1.package com.gwtsolutions.client;
2.
3.import com.google.gwt.user.client.ui.Widget;
4.import com.gwtsolutions.components.client.ui.dnd.DragSource;
5.
6.public class IpodDropTarget extends MusicPlayerDropTarget {
7.  public IpodDropTarget(Widget w) {
8.    super(w);
9.  }
10.
11.  public boolean acceptsDragSource(DragSource ds) {
12.    MusicPlayer mp =
13.        (MusicPlayer) ((MusicPlayerDragSource) ds).getWidget();
14.
15.    return mp.getInfo().startsWith("iPod");
16.  }
17.}

Listing 6.8. com.gwtsolutions.public.ZuneDropTarget

1.package com.gwtsolutions.client;
2.
3.import com.google.gwt.user.client.ui.Widget;
4.import com.gwtsolutions.components.client.ui.dnd.DragSource;
5.
6.public class ZuneDropTarget extends MusicPlayerDropTarget {
7.  public ZuneDropTarget(Widget w) {
8.    super(w);
9.  }
10.
11.  public boolean acceptsDragSource(DragSource ds) {
12.    MusicPlayer mp =
13.        (MusicPlayer) ((MusicPlayerDragSource) ds).getWidget();
14.
15.    return mp.getInfo().startsWith("Zune");
16.  }
17.}

The only thing that the drop targets specific to the music player do is define what kind of music player they will accept, by checking whether the component wrapped in the drag source is an iPod or a Zune.

Defining the CSS Classes

Listing 6.9 shows the CSS styles used by the application's drag source and drop targets.

Listing 6.9. com/gwtsolutions/public/css/styles.css

1. <style>
2.     body,td,a,div,.p{font-family:arial,sans-serif}
3.     div,td{color:#000000}
4.     a:link,.w,.w a:link{color:#0000cc}
5.     a:visited{color:#551a8b}
6.     a:active{color:#ff0000}
7.
8.     .dragPanel {
9.       border: thin solid darkGray;
10.       width: 400px;
11.       height: 400px;
12.       background: lightGray;
13.     }
14.
15.     .cartPanel {
16.       padding: 10px;
17.       border: thin solid darkGray;
18.       background: white;
19.       width: 250px;
20.       height: 125px;
21.     }
22.
23.     .pointerCursor {
24.       cursor: pointer;
25.     }
26.     .moveCursor {
27.       cursor: move;
28.     }
29.     .blueBorder {
30.       border: thin solid blue;
31.     }
32.     .noDropCursor {
33.      cursor: no-drop;
34.     }
35. </style>

Take note of the cursor styles—pointerCursor, moveCursor, noDropCursor—and the blueBorder style. Each of those styles has only one attribute, and the styles are added and removed from widgets. With GWT, it is not uncommon to define CSS styles with one attribute that are mixed in with other CSS styles for a single widget.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020