Welcome!

Adobe Flex Authors: Matthew Lobas, PR.com Newswire, Shelly Palmer, Kevin Benedict

Related Topics: Adobe Flex

Adobe Flex: Article

Building ToolTips

Building ToolTips

In many programs, if you keep the mouse over an area of the screen (for example, a button) for a short amount of time, a small text message pops up to describe what the area of the interface does. This is knows as a "tooltip." Tooltips have become a widely accepted way of making user interfaces clearer. The new user can use them to learn basic functionality. Users who have not used a piece of software for a long time can use them to refresh their memory. The experienced user will not be impacted by tooltips since one will only appear if the user hovers over an area for a significant amount of time.

Even in Director, the meanings of some of the buttons might not be immediately clear. In the Director main toolbar, there is a button with two right-angled arrows. The novice Director user might think that this is some sort of traffic diagram from England showing where cars may turn left (see Image I).

However, if you move the mouse over this button for a while, a tooltip shows up to explain the meaning of this button (see Image II).

This article shows how to build a set of two related behaviors that will implement tooltips in Director. The first behavior will be the "Tooltip Rollover." You can attach this behavior to any interface element you wish to have a tooltip. The other behavior will be the "Tooltip Display" behavior. This behavior will be attached to a single sprite made up of a field member. This one sprite will be used to display the text of the tooltip.

We'll discuss the following concepts:

  • Instances of behaviors
  • Events and event handlers
  • State machines
  • Timing in milliseconds
  • Intersprite communication
  • Calculating positions and rectangles on the Stage
Tooltip Rollover
First we'll discuss and write the Tooltip Rollover behavior. The Tooltip Rollover behavior will detect when the mouse has been within the rectangle of a sprite for a given amount of time, and then send the text to be displayed to the Tooltip Display sprite that lives in a different channel.

Let's think about the essential pieces before writing some code. Among the things we must do are the following:

  • Determine what text should be displayed
  • Build a timing mechanism to see if the user has kept the mouse inside the rectangle of the sprite for an appropriate amount of time
  • Find out where the Tooltip Display sprite is
  • Send text to the Tooltip Display sprite at the appropriate time
Text to Display
In Director each cast member can have a name. For simplicity, we will start by using the name of the rolled over member as the text of the tooltip. We can get this name by using the following code:

property spriteNum
property pName

on beginSprite me
   pName = sprite(spriteNum).member.name
end

"spriteNum" is a special property variable that can be used in behaviors. When it is declared as a property and used in a behavior, Director automatically gives it the number of the channel to which the behavior is attached.

One of the big buzz phrases in programming these days is object-oriented programming (also known as OOP). Behaviors are a great way of learning more about OOP. Programmers write behavior scripts. But when a behavior script is attached to a sprite, Director creates a new object from the script. Each such object is called an "instance" of that behavior.

Here's a simple example. Create a new Director movie. Go to the paint window and create a square. Name the member "Square". Then in the paint window, create a circle and name the member "Circle". Now open a script window and enter the code above. Before the last line (the "end" line) of the beginSprite handler, add the following line:

put "spriteNum" && spriteNum && "pName" && pName

Name this script "Tooltip Rollover". Using the Property Inspector, make sure that you set the type of this script to "Behavior".

Now drag the Square member into channel 1, and drag the Circle member into channel 2. Finally drag the Tooltip Rollover behavior script onto both sprites. Now run the movie.

If you open the message window, you should see the following:

--"spriteNum 1 pName Square"
--"spriteNum 2 pName Circle"

At run time, Director creates two instances (objects) from the single behavior script. Each instance uses the exact same code, but each instance gets its own copy of the data - the property variables. Each gets its own copy of spriteNum and its own copy of pName. As we will see in a moment, the value of any property variable declared in a behavior script is "remembered" and can be accessed by any other handler in that script.

Any change you make to the code in a behavior script will affect all sprites to which the behavior is attached. This is a very important part of object oriented programming.

Timing
Now we need to build a way for the behavior script to know when is the right time to show a tooltip. Again for simplicity, we'll just pick a set amount of time. Let's say that we will trigger a tooltip when the user has kept the mouse within the rectangle of the rolled-over item for one second.

To build this timing mechanism, we must understand two important concepts: the "on exitFrame" handler and the concept of a state machine. At each frame, Director sends out special messages to all sprites. One of these messages is the exitFrame message. The rate at which this message is sent is dependent on the frame rate of the Director movie. In a behavior, you can write on an exitFrame handler to receive this message. The content of the exitFrame message is completely up to the programmer. You can tell Director to do anything you want it to do on each such call. A "trick" is to make the same handler do different things under different circumstances. In our case, in the exitFrame handler, we can constantly check how long the mouse has been within our rectangle. If it has been over a second, we can make a call to display the tooltip.

But how do we do this checking? The answer lies in a concept called a state machine. When implemented in software, a state machine is a piece of code that does something different based on the value of a variable. This maps nicely into a Lingo case statement:

case someVariable of:
State1:
--execute this code here
State2:
-- execute this code here
...
StateN:
-- execute this code here
end case

The key is that in any branch of the state machine - or in other handlers in the same script - we can change the state to some other state.

Here's how we'll apply this idea to our Tooltip Rollover behavior. We will declare a property called psymState that will be used to keep track of what state the current behavior is in. In thinking through the different states, the behavior will be in one of three states:

  • #notOver: The mouse is not over our rectangle
  • #overAndWaiting: The mouse is over our rectangle and we are waiting for one second
  • #showing: The tooltip is showing
We'll start psymState in the #notOver state. Whenever the mouse enters our rectangle, we should go into the #overAndWaiting state. When we are in this state for one second, we trigger the tooltip to display, and change our state to #showing. Whenever the mouse leaves our rectangle, we hide the tooltip and change the state to #notOver.

In computer science classes, students are asked to draw "state diagrams" to describe these type of interactions. Another approach is to create a table with a list of events as rows (exitFrame, mouse-Enter, mouse-Leave), and a list of states as columns (#notOver, #overAndWaiting, #showing). This is often a good idea to be sure to account for all cases. In each cell, you describe what action takes place and any change in the state variable. Then the array is turned into code.

However, this state machine is rather simple and will become clearer with some simple code. Code I shows what this state machine would look like in pseudo-Lingo. Notice the addition of the Lingo on mouseEnter, on mouseDown, and on mouseUp handlers to handle these Lingo events.

By declaring psymState as a property variable, it means that each instance of this behavior will have its own version of psymState. Further, psymState can be used in any handler in the script, and its value will be remembered across these calls. For example, when the user moves the mouse into the rectangle of the sprite, the on mouseEnter handler is called by Director, and here we set the state to #overAndWaiting. The exitFrame handler is called many times each second. When the value of psymState changes, the exitFrame handler will do something different - it will take a different branch in the case statement.

To finish the timing aspect, we need to figure out how to count from zero to one second. There are many ways to do this, but here is the simplest. When the user first brings the mouse over the sprite, we'll calculate what time it will be one second from that point. Lingo keeps time in milliseconds. You can find out the current value of milliseconds from when the computer was turned on by using the Lingo function "the milliseconds". To find one second from the current time, we can add 1,000 to the milliseconds. We can save this value in a new property variable like this:

pmsShowTime = the milliseconds + 1000

Finally, in the exitFrame handler, in the #overAndWaiting part of the case statement, we can check for the one second elapsed by checking if the current value of the milliseconds is greater than the pmsEnd that we calculated earlier. If so, then we show the tooltip and change our state to #showing. The check looks like this:

   If the milliseconds > pmsShowTime then
     -- Show the tooltip
     psymState = #showing
   end if

It turns out that in this behavior script, the #waiting and #showing states don't really do anything, and they could be collapsed into a single state. However, for the sake of clarity, I like to show all possible states. It is also a good idea to keep these states in the code in case you decide to do something else when in one of these states.

There is one extra note here. If the rolled-over area is not a rectangle, for example a circle, you need to use Matte Ink in the score. When using Matte ink, Director will send the mouseEnter and mouseLeave messages only when the mouse enters and leaves a pixel that is in the cast member, not just within the rectangle of the sprite.

InterSprite Communication
The main thing that's left to do is to send a message to the Tooltip Display to show the tooltip. Obviously we have not written the Tooltip Display behavior yet. However, we can now define what messages we expect to send it. This is known as defining the "interface" of a behavior or an object. We know from our pseudo-code above that we will need to tell it to show and hide the tooltip. Clearly, we will need to define one handler for each of these actions. However, when we want to show a tooltip, thinking ahead, the code to show a tooltip will need to know two things: the text to display and the rectangle of the rolled-over item (in order to position the tooltip accurately). When the behavior instance starts up, we can save away the rectangle of the sprite in a property variable. When we call the show routine, we will need to pass in the text and this rectangle.

The final issue is to find out to which channel the Tooltip Display behavior instance is attached. The way to do this is to broadcast a message to all sprites and ask them if they have the Tooltip Display behavior attached. This can be done using sendAllSprites. But sendAllSprites can be "expensive" in terms of time, so we don't want to do this a lot. Here's how we will handle this: the first time we show a tooltip, we will use a sendAllSprites to send out a special message asking for the sprite number of the tooltip display sprite. When we find out the channel number, we will save it in yet another property variable. All property variables (in fact, all variables) start out with a value of VOID. We can use the voidP() function to check if we have figured out the channel number. From then on, whenever we want to send messages to the Tooltip Display behavior, we will use the saved channel number. When we want to send a message to the specific sprite with the Tooltip Display behavior attached, we use the sendSprite command.

Tooltip Rollover Code
Putting all this together, we get the code for the Tooltip Rollover (see Code II).

Notice that I added an on endSprite handler to the end of the script. This just sends a message to the Tooltip Display sprite to turn off the tooltip when the Rollover sprite ends.

Tooltip Display
Now we have to build the Tooltip Display behavior script. We know from our earlier discussion of the "interface" of this behavior, that this behavior script will at least need a Show, Hide, and GetChannel handler. Let's start by building a skeleton behavior script (see Code III).

The outline in Code III gives us most of the functionality we need. In fact, at this point, you can test if the intersprite communication is working correctly. To do this, create a field cast member and give it a name like "Tooltip Display Field". Drag it to the stage and place it in the highest-numbered channel. This way, the tooltip will show over all other sprites. In practice, this sprite will need to be stretched across the entire movie so that Tooltip Rollover behaviors can communicate with it from anywhere in the movie.

Now create a new behavior script, call it "Tooltip Display", and enter the code from Code III. Be sure to make it of type Behavior in the Behavior inspector. Finally, drag the behavior from the cast and drop it onto the field sprite in the score. Open the message window and run the program. When you hover over the square or the circle for one second, the word square or circle should appear in the message window, along with the appropriate rect.

Formatting the Text
When dealing with a field member, there are many different properties that can be manipulated to alter the way the text is displayed. You can find a list of these properties by clicking on the member in the cast, then looking at the field tab in the Property Inspector (see Image III).

Of these properties, for a tooltip display you will want to set:

  • editable to false
  • boxtype to #adjust
  • wordWrap to true
You can experiment with and customize many of the other properties here (e.g., border, color, bgColor, font, fontStyle, fontSize, etc.) so that the tooltip will appear the way you want it. Any changes you make here will be reflected for the display of all tooltips.

However, since the text to be displayed in the tooltip changes each time you rollover a different item, the rectangle (width and height) of the member needs to be set on the fly. Therefore, setting the rectangle must be done in code.

To begin the full Tooltip Display behavior, we will define a few properties for saving information, and set a few property variables as constants to be used in calculations later. At the end of beginSprite handler, we make a call to a move the tooltip off-screen so it is not visible at the start of the program (see Code IV).

An important thing to notice here is that in the first line, we "cache" away a reference to the tooltip member into pmTooltipText. This will make it easier to refer to the member in the rest of the code. Since Lingo only has to figure out this member reference once, it helps make the code fast. You'll also notice that one of the properties we created was called pMaxWidthTooltip. This will be used to set a maximum width for the tooltip. If the text goes over the maximum width, the text will wrap onto two or more lines. We'll pick an arbitrary size of 200 pixels to start width.

As we discussed earlier, when an instance of the Tooltip Rollover behavior instance calls the Tooltip Display instance, it will pass in the text to display, and the rectangle of the rolled over item. Now we have all the information we need to code the mTooltipDisplay_Show handler.

To size the rectangle properly for the tooltip, we first set the rectangle of the member our maximum width. Then we put the text into the display member:

on mTooltipDisplay_Show me, theString, rectRolledItem
   member(pmTooltipText).rect = rect(0, 0, pMaxWidthTooltip, 0)
   member(pmTooltipText).text = theString

When we put the text into the member, Director automatically adjusts the height of the rectangle for us, but it leaves the width at pMaxWidthTooltip. For multiline tooltips this is fine. However, if the tooltip is only one line of text, then we must manually adjust the right side of the tooltip member's rectangle.

Lingo has a routine called charPosToLoc that tells us the position of any character in a string. We want to know the position of the right edge of the last character. To do this, we ask Director the position of the number of characters in the string, plus one. While this is a non-existent character, Director gives us the width of the full string. Knowing this width, we can adjust the rest of the member. Here's how:

if pmTooltipText.lineCount = 1 then
   -- Only one line, must shrink the width to match the text
   nChars = pmTooltipText.text.char.count
   locLastChar = pmTooltipText.CharPosToLoc(nChars + 1)
   textMemberRect = pmTooltipText.rect
   textMemberRect.right = locLastChar.locH
   pmTooltipText.rect = textMemberRect
end if

Placing the Tooltip
Field members work differently from graphics members as far as the registration point is concerned. Since you can change text on the fly, field members have their registration point in the upper left hand corner. This makes the math slightly tricky. We will calculate the horizontal and vertical locations to display the tooltip separately.

We want to position the tooltip centered on, and a little below the rolled item. Earlier we declared a property variable, pnPixelsBelow, and set it a small number of pixels (4) to give us some separation from the rolled item. To display the tooltip we make the calculations shown here:

-- Calculate locH and locV
centerH = (rectRoll.left + rectRoll.right) / 2
locHTip - centerH - (pmToolTipText.width /2)
locVTip = rectRoll.bottom + pnPixelsBelow

Finally, we use the locV and the locH we just calculated to properly position the tooltip:

sprite(spriteNum).loc = point(locHTip, locVTip)

Code V is the resulting full script of the Tooltip Display behavior.

Extensions
We have shown the basic functionality of tooltips. In practice, there are a few things we would want to do to extend these behaviors.

In the Tooltip Rollover behavior, we would want the ability to alter the text to be displayed. Ideally, by default we could use the name of the cast member, but we would like to have the ability to change that to any text. Further, we would like to have the ability to change the delay period. While one second may be fine, we might like to set some tooltips to show up in less or more time.

Both of these can be accomplished relatively easily. To allow for these types of modifications, there is a very powerful handler called getPropertyDescription- List that can be built into the Tooltip Rollover behavior. Using getPropertyDescriptionList, we can specify that when the developer drops a behavior onto a sprite, Director will bring up a dialog box that shows defaults, but allows the developer to change values.

We would probably want the Tooltip Display behavior to be a little smarter about placement of the tooltip. If an interface element is too close to the bottom of the screen, we would want the tooltip to display above the item. Likewise, if the interface element is too close to the left or right edge, we would want the display to be positioned so that the entire tooltip could be readable on the stage.

Further, we might want to be able to modify more of the field properties such as Margin and Framing, and have the Tooltip Display behavior adjust automatically. Doing so requires a little more math in the mTooltipDisplay_Show method.

I am placing a fully functional and fully documented set of behaviors that includes these extensions in a sample movie on my Web site at: http://furrypants.com/ftp/tooltips.dir.

Conclusion
Tooltips have become valuable additions to improving the clarity of user interface designs. Using the two drag-and-drop behaviors described here, Director developers can now add this functionality quickly and easily.

More Stories By Irv Kalb

Irv Kalb has been working as an independent software developer in Director and Lingo for over ten years. He has written extensively on object oriented programming in Lingo, and his on-line Ebook on this topic can be found at www.furrypants.com/loope. Irv is always interested in discussing new projects.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices t...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
SYS-CON Events announced today that Cedexis will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
SYS-CON Events announced today that Google Cloud has been named “Keynote Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
SYS-CON Events announced today that Opsani will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.