问题描述
我的 Java 项目的 JFXPanel 中有一个 JavaFX ScrollPane。该项目将在没有键盘的触摸显示器中进行,因此我需要模拟触摸屏滚动。
问题是;如果我在 ScrollPane 中拖动鼠标,它工作正常,但如果我将鼠标拖动到有按钮的地方,它就无法滚动(这个想法是 ScrollPane 将填充按钮,它们之间没有空格)。
The white part and the buttons are inside ScrollPane
这是在我的代码中创建 ScrollPane 的部分。
private static Scene createScene(int wS,int hS) {
ScrollPane scrollPane = new ScrollPane();
FlowPane flowpane = new FlowPane();
scrollPane.setCache(true);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.setPannable(true);
for(int i=0; i<100; i++)
flowpane.getChildren().add((new ButtonProduct(wS,"Apple " + (i+1)));
scrollPane.setContent(flowpane);
Scene scene = new Scene(scrollPane);
return (scene);
}
编辑:
我在拖动按钮时添加了一个 MouseEvent,但我不知道如何“使滚动窗格被选中”来移动它。
public ButtonProduct(int wS,String t) {
this.setText(t);
this.setMinSize((int) (wS*sizeW),(int) (wS*sizeW));
this.setPrefSize((int) (wS*sizeW),(int) (wS*sizeW));
this.setMaxSize((int) (wS*sizeW),(int) (wS*sizeW));
this.setonDragDetected(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
System.out.println("Dragged Button");
e.consume();
}
});
}
解决方法
我找到了答案,这是 ScrollPane 中 Button(Node) 的代码。 但是您需要恢复按钮事件以获得更好的性能,这不是在下一个代码中开发的。
import javax.swing.*;
import java.awt.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.control.ScrollPane;
public class ButtonProduct extends Button {
private static double sizeW = .075;
//Constructor
public ButtonProduct(ScrollPane sC,int wS,String t) {
this.setText(t);
this.setMinSize((int) (wS*sizeW),(int) (wS*sizeW));
this.setPrefSize((int) (wS*sizeW),(int) (wS*sizeW));
this.setMaxSize((int) (wS*sizeW),(int) (wS*sizeW));
this.setOnDragDetected(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
((Button) e.getSource()).setEventDispatcher(sC.getEventDispatcher());
sC.requestFocus();
e.consume();
}
});
}
}