2014-07-23 38 views
1

繼教程here我嘗試使用下面的代碼創建一個ScrollPane一個工具提示:工具提示不顯示在滾動窗格

final ScrollPane scroll = new ScrollPane(); 

scroll.addEventHandler(MouseEvent.MOUSE_MOVED, new EventHandler<MouseEvent>() { 
     @Override 
     public void handle(MouseEvent t) { 
      pointer = MouseInfo.getPointerInfo(); 
      point = pointer.getLocation(); 
      color = robot.getPixelColor((int) point.getX(), (int) point.getY()); 
      Tooltip tooltip = new Tooltip(); 
      tooltip.setText(" " + color); 
      tooltip.activatedProperty(); 
      scroll.setTooltip(tooltip); 

      System.out.println("Color at: " + point.getX() + "," + point.getY() + " is: " + color); 
     } 

    }); 

然而,工具提示拒絕本身顯示在滾動窗格,但輸出的「Color at:...」正在打印,所以我確定該句柄正在被調用。

編輯:關於jewelsea的建議,我嘗試把eventHandler放在內容上,而不是窗格上,但沒有任何效果。

+0

似乎更可能是你想這個程序應用到滾動窗格,而不是滾動窗格本身的內容節點 - 當你這樣做會發生什麼? – jewelsea

+0

我修改了我的代碼的內容,在這種情況下是一個imageview,給了他eventHandler,但無濟於事。我甚至試圖把這個eventHandler放在我放在那裏的一個按鈕上,它也不起作用。 – BURNS

回答

2

如果我明白你要做什麼,你只需要安裝一次工具提示,然後在鼠標移動時修改它的文本。

這個工作對我來說:

import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.control.ScrollPane; 
import javafx.scene.control.Tooltip; 
import javafx.scene.image.Image; 
import javafx.scene.image.ImageView; 
import javafx.scene.image.PixelReader; 
import javafx.scene.input.MouseEvent; 
import javafx.scene.layout.BorderPane; 
import javafx.scene.paint.Color; 
import javafx.stage.Stage; 

public class ImageTooltipTest extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     BorderPane root = new BorderPane(); 
     Image image = new Image("http://www.publicdomainpictures.net/pictures/30000/velka/tropical-paradise.jpg"); 
     final ImageView imageView = new ImageView(); 
     imageView.setImage(image); 
     final ScrollPane scroller = new ScrollPane(); 
     scroller.setContent(imageView); 

     final Tooltip tooltip = new Tooltip(); 
     scroller.setTooltip(tooltip); 

     scroller.getContent().addEventHandler(MouseEvent.MOUSE_MOVED, event -> { 
      Image snapshot = scroller.getContent().snapshot(null, null); 
      int x = (int) event.getX(); 
      int y = (int) event.getY(); 
      PixelReader pixelReader = snapshot.getPixelReader(); 
      Color color = pixelReader.getColor(x, y); 
      String text = String.format("Red: %.2f%nGreen: %.2f%nBlue: %.2f", 
        color.getRed(), 
        color.getGreen(), 
        color.getBlue()); 
      tooltip.setText(text); 
     }); 



     root.setCenter(scroller); 
     Scene scene = new Scene(root, 800, 600); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 
+0

非常感謝你,先生!這可能是因爲新工具提示的初始化時間過長? – BURNS

+1

按照設計,工具提示在經過短暫的延遲之後纔會出現。因此,隨着鼠標移動,不斷將其重置爲新的工具提示可能會阻止它出現(儘管我實際上不知道實現細節)。 –

+0

確實如此,儘管我試圖讓我的鼠標保持10秒以上 – BURNS