簡體   English   中英

JavaFX 鼠標滾輪上的事件已為 ScrollPane 完成

[英]JavaFX event on Mouse Wheel Finished for ScrollPane

我有一個 ScrollPane 上面有很多元素(與這個JavaFX setHgrow / binding property expanding infinitely相同),最初我打算使用setOnScrollFinished(this::scrollFinished); 事件,但是我現在通過研究發現這只適用於觸摸手勢,並且試圖找到 MouseWheel 的折衷方案並不是很好,我只是找到了非常復雜的解決方案,這些解決方案並沒有真正解決我需要的問題。

我最多的是為滾動條的變化添加一個監聽器:

vvalueProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                System.out.println("scroll time");
            }
        });

然而,這在滾動時不斷觸發,我正在尋找的是只會在我停止滾動后才調用的東西。

我的最終目標是擁有一個系統,當我滾動時,它會運行一個事件,該事件將 go 通過我的每個元素,這樣我就可以為它們分配一個圖像,如果它們在 window 范圍內,並且它們會刪除圖像,如果它們不是。

這基本上是我的代碼,取自之前幫助過我的好用戶:

import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class ScrollPaneContentDemo extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        List<Item> items = new ArrayList<>();
        IntStream.range(1, 1000).forEach(i -> items.add(new Item()));
        TestPanel root = new TestPanel(items);
        Scene scene = new Scene(root, 500, 500);
        stage.setScene(scene);
        stage.setTitle("ScrollPaneContent Demo");
        stage.show();
    }

    class TestPanel extends ScrollPane {
        private final int SPACING = 5;
        private final int ROW_MAX = 6;
        private DoubleProperty size = new SimpleDoubleProperty();

        public TestPanel(List<Item> items) {
            final VBox root = new VBox();
            root.setSpacing(SPACING);
            HBox row = null;
            int count = 0;
            for (Item item : items) {
                if (count == ROW_MAX || row == null) {
                    row = new HBox();
                    row.setSpacing(SPACING);
                    root.getChildren().add(row);
                    count = 0;
                }

                CustomBox box = new CustomBox(item);
                box.minWidthProperty().bind(size);
                row.getChildren().add(box);
                HBox.setHgrow(box, Priority.ALWAYS);
                count++;
            }
            setFitToWidth(true);
            setContent(root);

            double padding = 4;
            viewportBoundsProperty().addListener((obs, old, bounds) -> {
                size.setValue((bounds.getWidth() - padding - ((ROW_MAX - 1) * SPACING)) / ROW_MAX);
                });


        //setOnScroll(this::showImages);       //The problematic things

        vvalueProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
            System.out.println("scroll test");           //The problematic things
        }
    });

        }
    }

    class CustomBox extends StackPane {
        private Item item;
        private Rectangle square;
               private int size = 20;

    public CustomBox(Item item) {
        setStyle("-fx-background-color:#99999950;");
        this.item = item;
        setPadding(new Insets(5, 5, 5, 5));
        square = new Rectangle(size, size, Color.RED);
        square.widthProperty().bind(widthProperty());
        square.heightProperty().bind(heightProperty());

        maxHeightProperty().bind(minWidthProperty());
        maxWidthProperty().bind(minWidthProperty());
        minHeightProperty().bind(minWidthProperty());
        getChildren().add(square);
    }
}

    class Item {
    }
}

您將必須偵聽屬性更改以檢測滾動而不會丟失。 不過,您不必在每次偵聽器觸發時都采取繁重的操作:只需記錄它發生的時間,然后進行循環過濾並在需要時觸發事件。 這是:

  1. 隨時注冊滾動值更改(或調整ScrollPane大小)
  2. 如果在超過 1 秒之前注冊了更改,則設置一個循環以較短的時間間隔(從用戶的角度來看)進行檢查。
  3. 發生這種情況時,讓ScrollPane觸發一個事件- 我們稱之為“滴答聲” -並取消注冊上次滾動

對於循環,我們將使用一個Timeline ,其中KeyFrame將有一個onFinished處理程序,大約每 100 毫秒在 JavaFX 應用程序線程上調用一次,以避免必須處理另一個線程。

class TickingScrollPane extends ScrollPane {

  //Our special event type, to be fired after a delay when scrolling stops
  public static final EventType<Event> SCROLL_TICK = new EventType<>(TickingScrollPane.class.getName() + ".SCROLL_TICK");

  // Strong refs to listener and timeline
  private final ChangeListener<? super Number> scrollListener; //Will register any scrolling
  private final Timeline notifyLoop;  //Will check every 100ms how long ago we last scrolled

  // Last registered scroll timing
  private long lastScroll = 0; // 0 means "no scroll registered"

  public TickingScrollPane() {
    super();

    /* Register any time a scrollbar moves (scrolling by any means or resizing)
     * /!\ will fire once when initially shown because of width/height listener */
    scrollListener = (_observable, _oldValue, _newValue) -> {
      lastScroll = System.currentTimeMillis();
    };
    this.vvalueProperty().addListener(scrollListener);
    this.hvalueProperty().addListener(scrollListener);
    this.widthProperty().addListener(scrollListener);
    this.heightProperty().addListener(scrollListener);
    //ScrollEvent.SCROLL works only for mouse wheel, but you could as well use it 

    /* Every 100ms, check if there's a registered scroll.
     * If so, and it's older than 1000ms, then fire and unregister it.
     * Will therefore fire at most once per second, about 1 second after scroll stopped */
    this.notifyLoop = new Timeline(new KeyFrame(Duration.millis(100), //100ms exec. interval
        e -> {
          if (lastScroll == 0)
            return;
          long now = System.currentTimeMillis();
          if (now - lastScroll > 1000) { //1000ms delay
            lastScroll = 0;
            fireEvent(new Event(this, this, SCROLL_TICK));
          }
        }));
    this.notifyLoop.setCycleCount(Timeline.INDEFINITE);
    this.notifyLoop.play();

  }

}

如果您的ScrollPane將在任何時候從場景中移除,您可能需要添加一個方法來停止TimeLine ,以避免它繼續運行並可能消耗 memory。

完整的可運行演示代碼:

package application;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.event.Event;
import javafx.event.EventType;
import javafx.geometry.BoundingBox;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

class TickingScrollPane extends ScrollPane {

  //Our special event type, to be fired after a delay when scrolling stops
  public static final EventType<Event> SCROLL_TICK = new EventType<>(TickingScrollPane.class.getName() + ".SCROLL_TICK");

  // Strong refs to listener and timeline
  private final ChangeListener<? super Number> scrollListener; //Will register any scrolling
  private final Timeline notifyLoop;  //Will check every 100ms how long ago we last scrolled

  // Last registered scroll timing
  private long lastScroll = 0; // 0 means "no scroll registered"

  public TickingScrollPane() {
    super();

    /* Register any time a scrollbar moves (scrolling by any means or resizing)
     * /!\ will fire once when initially shown because of width/height listener */
    scrollListener = (_observable, _oldValue, _newValue) -> {
      lastScroll = System.currentTimeMillis();
    };
    this.vvalueProperty().addListener(scrollListener);
    this.hvalueProperty().addListener(scrollListener);
    this.widthProperty().addListener(scrollListener);
    this.heightProperty().addListener(scrollListener);
    //ScrollEvent.SCROLL works only for mouse wheel, but you could as well use it 

    /* Every 100ms, check if there's a registered scroll.
     * If so, and it's older than 1000ms, then fire and unregister it.
     * Will therefore fire at most once per second, about 1 second after scroll stopped */
    this.notifyLoop = new Timeline(new KeyFrame(Duration.millis(100), //100ms exec. interval
        e -> {
          if (lastScroll == 0)
            return;
          long now = System.currentTimeMillis();
          if (now - lastScroll > 1000) { //1000ms delay
            lastScroll = 0;
            fireEvent(new Event(this, this, SCROLL_TICK));
          }
        }));
    this.notifyLoop.setCycleCount(Timeline.INDEFINITE);
    this.notifyLoop.play();

  }

}

public class TickingScrollPaneTest extends Application {
  
  @Override
  public void start(Stage primaryStage) {
    
    try {
      
      //Draw our scrollpane, add a bunch of rectangles in a VBox to fill its contents
      TickingScrollPane root = new TickingScrollPane();
      root.setPadding(new Insets(5));
      VBox vb = new VBox(6);
      root.setContent(vb);
      final int rectsCount = 10;
      for (int i = 0; i < rectsCount; i++) {
        Rectangle r = new Rectangle(Math.random() * 900, 60); //Random width, 60px height
        r.setFill(Color.hsb(360. / rectsCount * i, 1, .85));   //Changing hue (rainbow style)
        vb.getChildren().add(r);
      }
      
      //Log every scroll tick to console
      root.addEventHandler(TickingScrollPane.SCROLL_TICK, e -> {
        System.out.println(String.format(
            "%s:\tScrolled 1s ago to (%s)",
            LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME),
            getViewableBounds(root)
            ));
      });
      
      //Show in a 400x400 window
      Scene scene = new Scene(root, 400, 400);
      primaryStage.setScene(scene);
      primaryStage.setTitle("TickingScrollPane test");
      primaryStage.show();
    } catch (Exception e) {
      e.printStackTrace();
    }
    
  }
  
  
  /**
   * Calculate viewable bounds for contents for ScrollPane
   * given viewport size and scroll position
   */
  private static Bounds getViewableBounds(ScrollPane scrollPane) {
    Bounds vbds = scrollPane.getViewportBounds();
    Bounds cbds = scrollPane.getContent().getLayoutBounds();
    double hoffset = 0;
    if (cbds.getWidth() > vbds.getWidth())
      hoffset = Math.max(0, cbds.getWidth() - vbds.getWidth()) * (scrollPane.getHvalue() - scrollPane.getHmin()) / (scrollPane.getHmax() - scrollPane.getHmin());
    double voffset = 0;
    if (cbds.getHeight() > vbds.getHeight())
      voffset = Math.max(0, cbds.getHeight() - vbds.getHeight()) * (scrollPane.getVvalue() - scrollPane.getVmin()) / (scrollPane.getVmax() - scrollPane.getVmin());
    Bounds viewBounds = new BoundingBox(hoffset, voffset, vbds.getWidth(), vbds.getHeight());
    return viewBounds;
  }

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM