flex htmlText in tooltip created by TooltipManager - apache-flex

I need to show htmlText in custom tooltip created by TooltipManager.
Below is the code.
myToolTip = ToolTipManager.createToolTip(text, pt.x, pt.y, "errorTipAbove") as ToolTip;
myToolTip.setStyle("borderColor", "#FAF8CC");
myToolTip.setStyle("color", "black");
myToolTip.setStyle("fontSize","9");
I have tried the following thing.
http://flexscript.wordpress.com/2008/08/19/flex-html-tooltip-component/
But that works if we set htmlText to a tooltip eg: button.
Please help.

Just look inside the code of ToolTipManagerImpl and you'll get your answer. Here's how createToolTip function creates toolTip:
public function createToolTip(text:String, x:Number, y:Number,
errorTipBorderStyle:String = null, context:IUIComponent = null):IToolTip{
var toolTip:ToolTip = new ToolTip();
var sm:ISystemManager = context ? context.systemManager as ISystemManager:
ApplicationGlobals.application.systemManager as ISystemManager;
sm.topLevelSystemManager.addChildToSandboxRoot(
"toolTipChildren", toolTip as DisplayObject);
if (errorTipBorderStyle){
toolTip.setStyle("styleName", "errorTip");
toolTip.setStyle("borderStyle", errorTipBorderStyle);
}
toolTip.text = text;
sizeTip(toolTip);
toolTip.move(x, y);
// Ensure that tip is on screen?
// Should x and y for error tip be tip of pointy border?
// show effect?
return toolTip as IToolTip;
}
So your answer is:
Create your own utility class with your own implementation of createToolTip function. Copy all the code from Adobe's implementation and change
var toolTip:ToolTip = new ToolTip(); -> var toolTip:ToolTip = new HTMLToolTip();
using component from the page you mentioned.
PS: You need to copy sizeTip function as well.

Related

Removing background image from label in tornadofx

I have two css classes on a tornadofx label bound to a SimpleBooleanProperty. One which has a background image and a blue border and one which has no background image and a yellow border.
Snippet from View containing label:
val switch: SimpleBooleanProperty = SimpleBooleanProperty(false)
label("my label"){
toggleClass(UIAppStyle.style1, switch.not())
toggleClass(UIAppStyle.style2, switch)
}
Snippet from UIAppStyle:
s(style1){
textFill = Color.YELLOW
maxWidth = infinity
maxHeight = infinity
alignment = Pos.CENTER
backgroundImage += this::class.java.classLoader.getResource("img.png")!!.toURI()
backgroundPosition += BackgroundPosition.CENTER
backgroundRepeat += Pair(BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT)
borderColor += box(Color.BLUE)
}
s(style2){
textFill = Color.YELLOW
maxWidth = infinity
maxHeight = infinity
alignment = Pos.CENTER
borderColor += box(Color.YELLOW)
}
When switch = false, there is a background image and a blue border. When switch = true, there is the same background image and a yellow border. I'm not finding out how to get the background image to remove. Interestingly enough, if I add a different background image to style2, it changes correctly.
Edit: To remove two toggleClasses and introduce new strange problem:
class MyView : View(){
...
init{
...
row{
repeat(myviewmodel.numSwitches){
val switch = myviewmodel.switches[it]
val notSwitch = switch.not()
label("my label"){
addClass(UIAppStyle.style2)
toggleClass(UIAppStyle.style1, notSwitch)
}
}
}
}
This code snippet does not work for me. However, if I add private var throwsArray = mutableListOf<ObservableValue<Boolean>>() as a field of MyView and add notSwitch to the array, then the same exact code works. It's almost as if notSwitch is going out of scope and becoming invalidated unless I add it to a local array in the class?
I don’t understand why you want to have two different toggleClass for the same control. As you pointed out, the problem in your case is that when the backgroundImage is set, you need to set a new one in order to change it. But in your case, you only have to add the style without backgroundImage first and them set toggleClass with the style with backgroundImage. Like this:
label("my label"){
addClass(UIAppStyle.style2)
toggleClass(UIAppStyle.style1, switch)
}
button {
action {
switch.value = !switch.value;
}
}
Edit: This ilustrate what I'm talking about in comments:
class Example : View("Example") {
override val root = vbox {
val switch = SimpleBooleanProperty(false)
val notSwitch = switch.not()
label("my label"){
addClass(UIAppStyle.style2)
toggleClass(UIAppStyle.style1, notSwitch)
}
button("One") {
action {
switch.value = !switch.value;
}
}
button("Two") {
action {
notSwitch.get()
}
}
}
}
You can put the notSwitch.get() in any action and without trigger that action it does the work. Check how I put it in the action of button Two, but without clicking that button even once, it works.
This is actually some kind of hack, in order to achieve what you want. But I don’t see the reason why my initial solution with true as default value for property shouldn’t work.
Edited to do inverse of status
Here is simple example of a working toggle class using your styling:
class TestView : View() {
override val root = vbox {
val status = SimpleBooleanProperty(false)
label("This is a label") {
addClass(UIAppStyle.base_cell)
val notStatus = SimpleBooleanProperty(!status.value)
status.onChange { notStatus.value = !it } // More consistent than a not() binding for some reason
toggleClass(UIAppStyle.smiling_cell, notStatus)
}
button("Toggle").action { status.value = !status.value }
}
init {
importStylesheet<UIAppStyle>()
}
}
As you can see, the base class is added as the default, while styling with the image is in the toggle class (no not() binding). Like mentioned in other comments, the toggleClass is picky, additive in nature, and quiet in failure so it can sometimes be confusing.
FYI I got to this only by going through your github code and I can say with confidence that the not() binding is what screwed you in regards to the toggleClass behaviour. Everything else causing an error is related to other problems with the code. Feel free to ask in the comments or post another question.

Flot chart title option?

Does Flot have an option that can be set to give the chart a title? I'm not seeing one for the overall chart, just for the axes.
But I might have missed something.
I do not think this option exists. It is pretty easy, though, to title the plot using regular HTML. Just wrap a div around your "placeholder" div and add the title text to that.
after drawing flot chart (plot function) fill canvas with text (jsFiddle). Advantage of my solution is that you can save chart as image containing title on it.
example:
var c=document.getElementsByTagName("canvas")[0];
var canvas=c.getContext("2d");
var cx = c.width / 2;
var text="Flot chart title";
canvas.font="bold 20px sans-serif";
canvas.textAlign = 'center';
canvas.fillText(text,cx,35);
You can use hooks for that. For instance use the overlay hook, and implement your overlay functionality in a separate OverlayHandler
Here is an example, where the chartElement, chartDataand chartOptions are your HTML element and flot data and flot options, respectively.:
var plotOverlayHandler = function(plot, cvs) {
if(!plot) { return; }
var cvsWidth = plot.width() / 2;
var text = 'Flot chart-title!';
cvs.font = "bold 16px Open Sans";
cvs.fillStyle = "#666666";
cvs.textAlign = 'center';
cvs.fillText(text, cvsWidth, 30);
return cvs;
};
var plot = $.plot(chartElement, chartData, chartOptions);
plot.hooks.drawOverlay.push( plotOverlayHandler );
When exporting the canvas via the native toDataURL method, simply apply the OverlayHandler first. This allows for greater flexibility.
var elCanvas = $('canvas.flot-base').first();
var canvas = plotCanvasOverlay(elCanvas, elCanvas.get(0).getContext('2d'))
var dataUrl = canvas.toDataURL('image/png');
Pioja's answer is indeed a great one. His jsFiddle shows the full details. It is important to have the following included in your options:
canvas: true,
grid: {
margin: { top:50 }
}
This will then insert a nice chart title which can be included in the image if you export it.
Building on pioja's answer, the title can be set directly after the plot has been made with:
var plot = $.plot($("#"+PlotPlaceholder), data, options);
By using the getCanvas function:
var c = plot.getCanvas();
Now, just follow pioja's code to get:
var canvas=c.getContext("2d");
var cx = c.width / 2;
var text="Flot chart title";
canvas.font="bold 20px sans-serif";
canvas.textAlign = 'center';
canvas.fillText(text,cx,35);

errorTip on Flex ComboBox

I have a tooltip on a ComboBox but I much prefer the styling of the errorTip
(with the "tail").
I have replaced the tooltip with an errorTip, but now the ComboBox has a red
border.
I'm still pretty much a newb... is there a way to override the red border on the
ComboBox so that its' border is back to good ol' black?
thanks,
Mark
You'd probably want to create your own custom tooltip as errorTip is reserved for the validation system.
There's some info here about how to create your own. It's fairly straightforward if you want something simple.
Here's something I've used in the past:
The Actionscript:
private var infoToolTip:ToolTip;
private function showToolTip(evt:MouseEvent, text:String):void
{
var pt:Point = new Point(evt.currentTarget.x, evt.currentTarget.y);
// Convert the targets 'local' coordinates to 'global' -- this fixes the
// tooltips positioning within containers.
pt = evt.currentTarget.parent.contentToGlobal(pt);
infoToolTip = ToolTipManager.createToolTip(text, pt.x, pt.y, "errorTipAbove") as ToolTip;
infoToolTip.setStyle("borderColor", "#87B846");
infoToolTip.setStyle("color", "white");
var yOffset:int = infoToolTip.height + 5;
infoToolTip.y -= yOffset;
infoToolTip.x -= 5
}
// Remove the tooltip
private function killToolTip():void
{
ToolTipManager.destroyToolTip(infoToolTip);
}
Using the toolTip:
<mx:Image source="{myImageSource}" mouseOver="showToolTip(event, 'Hello there!')" mouseOut="killToolTip()" />

How to display a tooltip only if the mouse cursor is within certain coordinates?

Within my component, I'm drawing some rectangles as below:
var objGraphics:Graphics=graphics;
objGraphics.drawRect(start, end, total, 5);
objGraphics.endFill();
I need to display a custom tooltip for each rectange when the mouse cursor is hovering over it.
How can I do this? I'm using the MouseMove event to track when the cursor moves over these coordinates (that part is working), but when I change the tooltip text it's not refreshing.
private function this_MOUSE_MOVE(event:MouseEvent):void
{
//...some code to check the coordinates to find out which rectangle the cursor
//is over
//current tooltip is "Rectangle A";
ToolTipManager.destroyToolTip(_myToolTip);
var localPoint:Point=new Point(event.localX, event.localY);
var globalPoint:Point=new Point(localToGlobal(localPoint).x,
localToGlobal(localPoint).y);
//cursor is over Rectangle B, so changing the tooltip;
_myToolTip=ToolTipManager.createToolTip("Rectangle B",
globalPoint.x, globalPoint.y) as ToolTip;
callLater(addChild, [_myToolTip]);
}
Thanks for your help.
EDIT: The problem seems to be with the following line:
ToolTipManager.destroyToolTip(_myToolTip);
If I comment out the preceding line, it will display the new tooltip, but it will keep creating new ones and the old ones never get removed. But if I add that line, it doesn't add any tooltips! Is the code not being executed sequentially, i.e., is the code to remove the tooltip somehow getting executed after the code to add the tooltip?
Assuming what you're adding to the stage, is called "myShape", you could do something like this:
// in your class...
private var var tooltip:Tooltip; // Or whatever your tooltip is
myShape.addEventListener(MouseEvent.MOUSE_OVER, handleOver);
myShape.addEventListener(MouseEvent.MOUSE_OUT, handleOut);
private function handleOver(evt:MouseEvent):void
{
// Show here
// OR
// tooltip = new Tooltip();
// addChild(tooltip);
}
private function handleOut(evt:MouseEvent):void
{
// Hide here
// OR
// removeChild(tooltip);
}
Hope this helps.

Styling UITextField

I've been playing around with different methods of determining at runtime the width of a "label" so that I can resize the "label" because I don't want it to truncate. I've finally found an easy solution through UITextField which allows me to set the .autoSize which is great! However, now I'm trying to "style" (simply adjust font and font size) of the UITextField but it seems that I have to do it manually with '.htmlText' (which I'll gladly accept if that is the ONLY way).
I'm using the .text to set the value of the label.
My test case involves a HBox (I'm actually using a Grid but they should be the same and I've done testing on both):
I style the HBox and the style carries through to the UITextField. I don't believe this will work for me because I have other components inside that I need to style differently.
I've tried: UITextFormat and TextFormat (I see that the .htmlText being updated accordingly but the output doesn't update. Then I noticed that whenever I called hbox.addChild(myUITextField) it would override the .htmlText
I've tried setting the style with myUITextField.setStyle("fontSize", 20) before and/or after the call to addChild neither of which made an impact on the display as per what I noted above.
Changes are being made but they seem to be overrided when I add it to the display.
So what do I need to do in order to style the UITextField aside from manually setting it along with my contents in .htmlText? Solutions not using UITextField is fine as long as there is some easy way of not truncating the text.
EDIT: I want to just do textField.setStyle('fontSize', 20) and expect that every time I change the text, I wouldn't need to use HTML to go with it (so I can just do textField.text = 'something else' and expect that it will still have a font size of 20). This is what I meant by not using .htmlText (sorry if I wasn't clear before).
2nd EDIT: I guess I should present the whole issue and maybe that'll clarify what I did wrong or couldn't achieve.
My intent is to have a Grid and add text into it. I do not want it to wrap or scroll so I add it to the next row in the Grid when the current row's children total width exceeds some number. In order to add it to the next row, I need to be able to calculate the width of the text. I would like to be able to style that text individually based on cases and there might be other components (like a TextInput). Essentially what I'm trying to accomplish is "Fill in the Blank".
I've included code to show what I'm currently doing and it works somewhat. It might be un-related to the original issue of styling but I can't figure out how to adjust the distance between each UITextField but aside from that this fits what I would like to accomplish. Relevant to the question is: I would like to change the way I style each UITextField (currently setting .htmlText) into something a bit straightforward though like I previously mentioned I'll gladly accept using .htmlText if that's the only solution.
So I have a Grid with x Rows in it and in each row, I have exactly one GridItem. Based on the input, I add UITextField and TextInput into the GridItem going on to the next GridItem when necessary. If you have a better way of doing so then that would be better but I guess what I really want is to find a different way of styling.
Also another problem, I'm not sure of the exact way to add a TextField into the display. I tried:
var t : TextField = new TextField();
t.text = "I'm a TextField";
hBox.addChild(t); // doesn't work
//this.addChild(t); // doesn't work either
But I get the following error:
TypeError: Error #1034: Type Coercion failed: cannot convert flash.text::TextField#172c8f9 to mx.core.IUIComponent.
Here's what I have that's working.
private function styleQuestionString(str : String) : String {
return '<FONT leading="1" face="verdana" size="20">' + str + '</FONT>';
}
private function loadQuestion(str : String) : void {
/* Split the string */
var tmp : Array = str.split("_");
/* Track the current width of the GridItem */
var curWidth : int = 0;
/* Display components that we will add */
var txtField : UITextField = null;
var txtInput : TextInput = null;
/* Track the current GridItem */
var curGridItem : GridItem = null;
/* Track the GridItem we can use */
var gridItemAC : ArrayCollection = new ArrayCollection();
var i : int = 0;
/* Grab the first GridItem from each GridRow of Grid */
var tmpChildArray : Array = questionGrid.getChildren();
for (i = 0; i < tmpChildArray.length; i++) {
gridItemAC.addItem((tmpChildArray[i] as GridRow).getChildAt(0));
}
curGridItem = gridItemAC[0];
gridItemAC.removeItemAt(0);
/* Used to set the tab index of the TextInput */
var txtInputCounter : int = 1;
var txtFieldFormat : UITextFormat = new UITextFormat(this.systemManager);
txtFieldFormat.leading = "1";
//var txtFieldFormat : TextFormat = new TextFormat();
//txtFieldFormat.size = 20;
/* Proper Order
txtField = new UITextField();
txtField.text = tmp[curItem];
txtField.autoSize = TextFieldAutoSize.LEFT;
txtField.setTextFormat(txtFieldFormat);
*/
var txtLineMetrics : TextLineMetrics = null;
var tmpArray : Array = null;
curGridItem.setStyle("leading", "1");
var displayObj : DisplayObject = null;
for (var curItem : int= 0; curItem < tmp.length; curItem++) {
/* Using UITextField because it can be auto-sized! */
/** CORRECT BLOCK (ver 1)
txtField = new UITextField();
txtField.text = tmp[curItem];
txtField.autoSize = TextFieldAutoSize.LEFT;
txtField.setTextFormat(txtFieldFormat);
***/
tmpArray = (tmp[curItem] as String).split(" ");
for (i = 0; i < tmpArray.length; i++) {
if (tmpArray[i] as String != "") {
txtField = new UITextField();
txtField.htmlText = styleQuestionString(tmpArray[i] as String);
//txtField.setTextFormat(txtFieldFormat); // No impact on output
txtLineMetrics = curGridItem.measureHTMLText(txtField.htmlText);
curWidth += txtLineMetrics.width + 2;
if (curWidth >= 670) {
curGridItem = gridItemAC[0];
curGridItem.setStyle("leading", "1");
if (gridItemAC.length != 1) {
gridItemAC.removeItemAt(0);
}
// TODO Configure the proper gap distance
curWidth = txtLineMetrics.width + 2;
}
displayObj = curGridItem.addChild(txtField);
}
}
//txtField.setColor(0xFF0000); // WORKS
if (curItem != tmp.length - 1) {
txtInput = new TextInput();
txtInput.tabIndex = txtInputCounter;
txtInput.setStyle("fontSize", 12);
txtInputCounter++;
txtInput.setStyle("textAlign", "center");
txtInput.width = TEXT_INPUT_WIDTH;
curWidth += TEXT_INPUT_WIDTH;
if (curWidth >= 670) {
curGridItem = gridItemAC[0];
if (gridItemAC.length != 1) {
gridItemAC.removeItemAt(0);
}
// TODO Decide if we need to add a buffer
curWidth = TEXT_INPUT_WIDTH + 2;
}
curGridItem.addChild(txtInput);
txtInputAC.addItem(txtInput);
/* Adds event listener so that we can perform dragging into the TextInput */
txtInput.addEventListener(DragEvent.DRAG_ENTER, dragEnterHandler);
txtInput.addEventListener(DragEvent.DRAG_DROP, dragDropHandler);
txtInput.addEventListener(DragEvent.DRAG_EXIT, dragExitHandler);
}
/* Add event so that this label can be dragged */
//txtField.addEventListener(MouseEvent.MOUSE_MOVE, dragThisLabel(event, txtField.text));
}
}
After about 8 hours of searching for a solution to what would seem to be such a simple issue I FINALLY stumbled on your posts here... Thankyou!!!
I have been stumbling around trying to get TextField to work and had no Joy, Label was fine, but limited formatting, and I need to be able to use embedded fonts and rotate. After reading the above this finally worked for me:
var myFormat:TextFormat = new TextFormat();
myFormat.align = "center";
myFormat.font = "myFont";
myFormat.size = 14;
myFormat.color = 0xFFFFFF;
var newTxt:UITextField = new UITextField();
newTxt.text = "HELLO";
addChild(newTxt);
newTxt.validateNow();
newTxt.setTextFormat(myFormat);
The order of addChild before the final 2 steps was critical! (myFont is an embedded font I am using).
One again... a thousand thankyou's...
John
EDIT BASED ON THE ASKERS FEEDBACK:
I didn't realize you wanted to just apply one style to the whole textfield, I thought you wanted to style individual parts. This is even simpler for you, won't give you any trouble at all :)
var textFormat: TextFormat = new TextFormat("Arial", 12, 0xFF0000);
myText.setTextFormat(textFormat);
Be aware that this sets the style to the text that is in the TextField, not necessarily future text you put in. So have your text in the field before you call setTextFormat, and set it again every time you change it just to be sure it stays.
It's probably best if you use a normal TextField as opposed to the component. If you still want the component you may need to call textArea.validateNow() to get it to update with the new style (not 100% sure on that one though) Adobe components are notoriously bad, and should be avoided. :(
To see all available options on the TextFormat object see here
END EDIT ---------
This is easy enough to just do with CSS in a normal old TextField.
var myCSS: String = "Have some CSS here, probably from a loaded file";
var myHTML: String = "Have your HTML text here, and have it use the CSS styles";
// assuming your textfield's name is myText
var styleSheet: StyleSheet = new StyleSheet();
styleSheet.parseCSS(myCSS);
myText.autoSize = TextFieldAutoSize.LEFT;
myText.styleSheet = styleSheet;
myText.htmlText = myHTML;
Supported HTML tags can be found here
Supported CSS can be found here
The reason you have a problem adding Textfield to containers is that it doesn't implement the IUIComponent interface. You need to use UITextField if you want to add it. However, that's presenting me with my own styling issues that brought me to this question.
A few things I know:
TextField is styled using the TextFormat definition, and applying it to the textfield. As Bryan said, order matters.
setStyle does nothing on IUITextField, and the TextFormat method doesn't seem to work the same as in normal TextFields. (Edit #2: Ahah. You need to override the "validateNow" function on UITextFields to use the setTextFormat function)
To autosize a TextArea, you need to do something like this (inheriting from TextArea):
import mx.core.mx_internal;
use namespace mx_internal;
...
super.mx_internal::getTextField().autoSize = TextFieldAutoSize.LEFT;
this.height = super.mx_internal::getTextField().height;
Found this code on, I think, on StackOverflow a while back. Apologies to the original author. But the idea is that you need to access the "mx_internal" raw textfield.
Text and TextArea have wrapping options. (Label does not). So if you set the explicit width of a Text object, you might be able to size using the measuredHeight option and avoid truncation.
(edit: That was #4, but stackoverflow parsed it into a 1...)

Resources