以下是一个示例代码,展示如何使用焦点侦听器来标记和缩放图像标签。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ImageTaggingExample extends Application {
private final double MIN_SCALE = 0.1;
private final double MAX_SCALE = 10.0;
private final double SCALE_DELTA = 1.1;
private ImageView imageView;
private Label zoomLabel;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
imageView = new ImageView("image.jpg");
imageView.setPreserveRatio(true);
imageView.setFitWidth(400);
zoomLabel = new Label("Zoom: 100%");
VBox root = new VBox();
root.getChildren().addAll(imageView, zoomLabel);
Scene scene = new Scene(root, 400, 400);
scene.setOnScroll(this::handleScroll);
primaryStage.setScene(scene);
primaryStage.show();
}
private void handleScroll(ScrollEvent event) {
event.consume();
double scaleFactor = SCALE_DELTA;
if (event.getDeltaY() < 0) {
scaleFactor = 1.0 / SCALE_DELTA;
}
double currentScale = imageView.getScaleX();
double newScale = currentScale * scaleFactor;
if (newScale < MIN_SCALE || newScale > MAX_SCALE) {
return;
}
imageView.setScaleX(newScale);
imageView.setScaleY(newScale);
zoomLabel.setText("Zoom: " + (int)(newScale * 100) + "%");
}
}
在上面的示例中,我们创建了一个包含图像标签和一个用于显示缩放级别的标签的垂直框。我们还创建了一个handleScroll
方法来处理滚动事件。在滚动事件中,我们根据滚动方向和缩放因子来计算新的缩放级别。然后,我们将新的缩放级别应用于图像标签,并更新缩放级别的标签。