A perfect java blog

Custom ToolTip on JavaFX

3 January,2011Narayan G. Maharjan

Hello I’m here to show you the new ToolTip which you can customize as you like! My Tooltip is little bit messy process but it takes very less memory. You can easily apply my Tooltip to your desired application. Here the code goes:

My CustomNode who uses the tooltip..

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

classMyCustomNodeextendsCustomNode{

//ToolTip node

publicvartooltip:MyToolTip;

//the text of tooltip

publicvartext:String;

//main node

publicvarnode:Node;

publicoverride functioncreate():Group{

returnGroup{

onMouseMoved:function(e:MouseEvent):Void{

tooltip.text=text;

tooltip.visible=true;

tooltip.layoutX=e.x+100;//or your desired x

tooltip.layoutY=e.y;//or your desired y

}

onMouseExited:function(e:MouseEvent):Void{

tooltip.visible=false;

}

content:[

node

]

}

}

}

Till here there is something little bit different. I used a new tooltip variable which has datatypes of MyToolTip. Ok I’ll show you what the MyToolTip class is:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

classMyToolTipextendsCustomNode{

publicvartext:String;

publicoverride functioncreate():Group{

returnGroup{

content:[

Rectangle{

width:bind text.length()*15

height:25

fill:Color.web("#f5f761");

arcWidth:5

arcHeight:5

effect:DropShadow{

offsetX:0

offsetY:0

color:Color.BLACK

radius:5

}

}

Text{

font:Font{

size:15

}

fill:Color.BLACK

x:10,y:20

content:bind text

}

]

}

}

}

You can see there is nothing new on MyTooltip it’s all about using simple graphics and text. Now the main class goes here:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

def tooltip=MyToolTip{

}

def node1=MyCustomNode{

text:"node1";

tooltip:tooltip;

node:Rectangle{

x:10,y:10

width:140,height:90

fill:Color.BLUE

}

}

def node2=MyCustomNode{

text:"node2";

tooltip:tooltip;

node:Rectangle{

x:10,y:10

width:140,height:90

fill:Color.RED

}

}

def hbox:HBox=HBox{

content:[node1,node2]

onMouseMoved:function(e:MouseEvent):Void{

println(e.x);

tooltip.visible=true;

tooltip.layoutX=e.x;//or your desired x

tooltip.layoutY=e.y;//or your desired y

}

onMouseExited:function(e:MouseEvent):Void{

println(e.x);

tooltip.visible=false;

}

}

Stage{

title:"Application title"

scene:Scene{

width:500

height:500

content:[

hbox,tooltip

]

}

}

Now you can see the main thing is ; I’m using a single MyToolTip which controls all the nodes tooltip. That’s all . Thanks for watching the post. You can see the demo at below launch button.