我有一个ScrollPane,上面有很多元素,(与这个JavaFX setH增长/绑定属性无限扩展相同),最初我计划使用setOnScrollFinated(这::scrollFinated);
事件,但是我现在通过研究发现这只适用于触摸手势,并且试图为MouseWheel找到一个折衷方案并不是很好,我只是找到了非常复杂的解决方案,并没有真正解决我需要的问题。
我最多只能在滚动条上添加一个监听器来更改:
vvalueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("scroll time");
}
});
然而,当滚动时,这会持续激发,我正在寻找的是一个只有在我停止滚动一秒钟后才会调用的东西。
我的最终目标是建立一个系统,当我滚动时,它将运行一个事件,该事件将遍历我的每个元素,这样,如果它们在窗口范围内,我就可以为它们分配一个图像,如果它们不在窗口范围内,它们就会删除图像。
这基本上是我的代码,取自之前帮助过我的优秀用户:
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 {
}
}
您必须监听属性更改以检测滚动而不丢失。不过,你不必每次监听器触发时都采取沉重的行动:只需记录事件发生的时间,然后进行循环过滤,并在需要时触发事件。这是这样的:
ScrollPane
调整大小)时注册ScrollPane
触发一个事件-让我们称之为“勾选”-并取消注册最后一个滚动对于循环,我们将使用一个Timeline
,其中KeyFrame
s将在JavaFX应用程序线程上大约每100毫秒调用一个onFinish
处理程序,以避免不得不处理另一个线程。
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();
}
}
如果要在任何时候从场景中删除滚动窗格
,可能需要添加一种方法来停止时间线
,以避免它继续运行并可能消耗内存。
完整的可运行演示代码:
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);
}
}
鼠标事件是Web 开发中最常用的一类事件,毕竟鼠标还是最主要的定位设备。DOM3 级事件中定义了9 个鼠标事件,简介如下。 click:在用户单击主鼠标按钮(一般是左边的按钮)或者按下回车键时触发。这一点对确保易访问性很重要,意味着onclick 事件处理程序既可以通过键盘也可以通过鼠标执行。 dblclick:在用户双击主鼠标按钮(一般是左边的按钮)时触发。从技术上说,这个事件并不是DOM2 级
本文向大家介绍解析javascript中鼠标滚轮事件,包括了解析javascript中鼠标滚轮事件的使用技巧和注意事项,需要的朋友参考一下 所有的现代浏览器都支持鼠标滚轮,并且在用户滚动滚轮时触发时间。浏览器通常使用鼠标滚轮滚动或缩放文档,但可以通过取消mousewheel事件来阻止这些默认操作。有一些互用性问题影响滚轮事件,但是编写跨平台的代码依旧可以行。除了Firefox之外的所有浏览器都支持
问题内容: 有没有一种方法可以在jQuery中获取鼠标滚轮事件(而不是谈论事件)? 问题答案:
本文向大家介绍javascript监听鼠标滚轮事件浅析,包括了javascript监听鼠标滚轮事件浅析的使用技巧和注意事项,需要的朋友参考一下 我们都见到过这些效果,用鼠标滚轮实现某个表单内的数字增加减少操作,或者滚轮控制某个按钮的左右,上下滚动。这些都是通过js对鼠标滚轮的事件监听来实现的。今天这里介绍的是一点简单的js对于鼠标滚轮事件的监听。 不同浏览器不同的事件 首先,不同的浏览器有不同的滚
本文向大家介绍html中鼠标滚轮事件onmousewheel的处理方法,包括了html中鼠标滚轮事件onmousewheel的处理方法的使用技巧和注意事项,需要的朋友参考一下 滚轮事件是不同浏览器会有一点点区别,一个像Firefox使用DOMMouseScroll ,ff也可以使用addEventListener方法绑定DomMouseScroll事件,其他的浏览器滚轮事件使用mousewheel
问题内容: 在鼠标滚轮上滚动它执行水平滚动。 已编辑 好吧,firebug说他在用 问题答案: 看来他只是将mousewheel事件映射到滚动区域。在IE中,仅通过使用方法就非常容易-滚动水平条的量为垂直条通常滚动的量。其他浏览器不支持该方法,因此您必须随心所欲地滚动任意数量: