2.X了JavaFx:如何写在图表上的文字?(JavaFx 2.x: How to write te

2019-08-04 01:41发布

通过图表上点击鼠标左键,我想通过创建一个文本区域矩形,这样才能够调整并移动到写入文本。

任何帮助非常感谢

编辑 :你好sarcan非常感谢你的善意回应。

我想你的代码,它编译并绘制一个区域图与注释,非常伟大的工作!

我现在需要改变的方式你的代码能够与键键盘输入一旦离开鼠标单击打印注解的现在不是。

下面是完整的代码

import javafx.application.Application;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.AreaChart;
import javafx.scene.chart.Axis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.Label;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

/**
*
* @author sarcan
*/
public class SampleApp extends Application {

public class SampleChart extends AreaChart<Number, Number> {
public SampleChart() {
    super(new NumberAxis(), new NumberAxis());

    getXAxis().setLabel("X");
    getYAxis().setLabel("Y");

    final Series<Number, Number> data = new Series<Number, Number>();
    data.setName("Dummy data");
    data.getData().addAll(
            new Data<Number, Number>(0,4),
            new Data<Number, Number>(1,5),
            new Data<Number, Number>(2,6),
            new Data<Number, Number>(3,5),
            new Data<Number, Number>(4,5),
            new Data<Number, Number>(5,7),
            new Data<Number, Number>(6,8),
            new Data<Number, Number>(7,9),
            new Data<Number, Number>(8,7)
    );

    getData().add(data);
}
}

public class ChartAnnotationNode {
private final Node _node;
private double _x;
private double _y;

public ChartAnnotationNode(final Node node, final double x, final double y) {
    _node = node;
    _x = x;
    _y = y;
}

public Node getNode() {
    return _node;
}

public double getX() {
    return _x;
}

public double getY() {
    return _y;
}

public void setX(final double x) {
    _x = x;
}

public void setY(final double y) {
    _y = y;
}
}

public class ChartAnnotationOverlay extends Pane {
private ObservableList<ChartAnnotationNode> _annotationNodes;
private XYChart<Number, Number> _chart;

public ChartAnnotationOverlay(final XYChart<Number, Number> chart) {
    _chart = chart;

    /* Create a list to hold your annotations */
    _annotationNodes = FXCollections.observableArrayList();

    /* This will be our update listener, to be invoked whenever the chart changes or annotations are added */
    final InvalidationListener listener = new InvalidationListener() {
        @Override
        public void invalidated(final Observable observable) {
            update();
        }
    };
    _chart.needsLayoutProperty().addListener(listener);
    _annotationNodes.addListener(listener);

    /* Add new annotations by shift-clicking */
    setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(final MouseEvent mouseEvent) {
            if (mouseEvent.getButton() == MouseButton.PRIMARY  && mouseEvent.isShiftDown())
                addAnnotation(mouseEvent.getX(), mouseEvent.getY());
        }
    });
}

/**
 * Invoked whenever the chart changes or annotations are added. This basically does a relayout of the annotation nodes.
 */
private void update(){
    getChildren().clear();

    final Axis<Number> xAxis = _chart.getXAxis();
    final Axis<Number> yAxis = _chart.getYAxis();

    /* For each annotation, add a circle indicating the position and the custom node right next to it */
    for (ChartAnnotationNode annotation : _annotationNodes) {
        final double x = xAxis.localToParent(xAxis.getDisplayPosition(annotation.getX()), 0).getX() + _chart.getPadding().getLeft();
        final double y = yAxis.localToParent(0,yAxis.getDisplayPosition(annotation.getY())).getY() + _chart.getPadding().getTop();

        final Circle indicator = new Circle(3);
        indicator.setStroke(Color.BLUEVIOLET);
        indicator.setCenterX(x);
        indicator.setCenterY(y);

        getChildren().add(indicator);

        final Node node = annotation.getNode();
        getChildren().add(node);
        node.relocate(x + 10, y - node.prefHeight(Integer.MAX_VALUE) / 2);
        node.autosize();
    }
}

/**
 * Add a new annotation for the given display coordinate.
 */
private void addAnnotation(final double displayX, final double displayY){
    final Axis<Number> xAxis = _chart.getXAxis();
    final Axis<Number> yAxis = _chart.getYAxis();

    final double x = (xAxis.getValueForDisplay(xAxis.parentToLocal(displayX, 0).getX() - _chart.getPadding().getLeft())).doubleValue();
    final double y = (yAxis.getValueForDisplay(yAxis.parentToLocal(0, displayY).getY() - _chart.getPadding().getTop())).doubleValue();

    if (xAxis.isValueOnAxis(x) && yAxis.isValueOnAxis(y))
        _annotationNodes.add(new ChartAnnotationNode(new Label("Annotation "+System.currentTimeMillis()), x, y));
}
}


@Override
public void start(final Stage stage) throws Exception {
    final SampleChart chart = new SampleChart();

    final ChartAnnotationOverlay overlay = new ChartAnnotationOverlay(chart);

    final StackPane stackPane = new StackPane();
    stackPane.getChildren().addAll(chart, overlay);

    final Scene scene = new Scene(stackPane);
    stage.setScene(scene);
    stage.setWidth(800);
    stage.setHeight(600);
    stage.show();
}

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

Answer 1:

1)我想通过把图的StackPane内开始。 在图表的顶部我把锚窗格后点击鼠标按住文本字段。

2)当用户点击图表,我会用图表的坐标轴来确定是否点击了绘图区和“价值”内被点击(使用NumberAxis#getValueForDisplay()

3)然后,我会为了增加听众图表通知的任何更改(内容,宽度,高度等)和适应总是显示接近相同值的文本区域的位置。

调整大小/直进,请让我们知道,让你任何麻烦。

编辑:按照要求,这里是一些示例代码。 下面的代码提供了一个简单的例子,让你按shift单击文本节点(我会打电话给他们的注释)添加到图表。 拖动或编辑注释是直接的,但我想保持示例简洁。

允许通过定义一个示例图表开始:

public class SampleChart extends AreaChart<Number, Number> {
    public SampleChart() {
        super(new NumberAxis(), new NumberAxis());

        getXAxis().setLabel("X");
        getYAxis().setLabel("Y");

        final Series<Number, Number> data = new Series<Number, Number>();
        data.setName("Dummy data");
        data.getData().addAll(
                new Data<Number, Number>(0,4),
                new Data<Number, Number>(1,5),
                new Data<Number, Number>(2,6),
                new Data<Number, Number>(3,5),
                new Data<Number, Number>(4,5),
                new Data<Number, Number>(5,7),
                new Data<Number, Number>(6,8),
                new Data<Number, Number>(7,9),
                new Data<Number, Number>(8,7)
        );

        getData().add(data);
    }
}

没什么特别的,到目前为止,我只是创建了一些随机模拟数据的区域图。

对于文本节点(或注释),我已经创建包含注释的X / Y值(不显示位置)和将用户自定义的节点将被渲染一个简单的POJO:

public class ChartAnnotationNode {
    private final Node _node;
    private double _x;
    private double _y;

    public ChartAnnotationNode(final Node node, final double x, final double y) {
        _node = node;
        _x = x;
        _y = y;
    }

    public Node getNode() {
        return _node;
    }

    public double getX() {
        return _x;
    }

    public double getY() {
        return _y;
    }

    public void setX(final double x) {
        _x = x;
    }

    public void setY(final double y) {
        _y = y;
    }
}

有趣的事情发生在什么之内我会称之为覆盖:一个透明的面板,将被放置在图表上。 请注意,我没有,最初建议,选择AnchorPane,尽管这会工作为好。 此外,这种实现是不完全的最有效的方法,但我想保持示例简单。

public class ChartAnnotationOverlay extends Pane {
    private ObservableList<ChartAnnotationNode> _annotationNodes;
    private XYChart<Number, Number> _chart;

    public ChartAnnotationOverlay(final XYChart<Number, Number> chart) {
        _chart = chart;

        /* Create a list to hold your annotations */
        _annotationNodes = FXCollections.observableArrayList();

        /* This will be our update listener, to be invoked whenever the chart changes or annotations are added */
        final InvalidationListener listener = new InvalidationListener() {
            @Override
            public void invalidated(final Observable observable) {
                update();
            }
        };
        _chart.needsLayoutProperty().addListener(listener);
        _annotationNodes.addListener(listener);

        /* Add new annotations by shift-clicking */
        setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(final MouseEvent mouseEvent) {
                if (mouseEvent.getButton() == MouseButton.PRIMARY  && mouseEvent.isShiftDown())
                    addAnnotation(mouseEvent.getX(), mouseEvent.getY());
            }
        });
    }

    /**
     * Invoked whenever the chart changes or annotations are added. This basically does a relayout of the annotation nodes.
     */
    private void update(){
        getChildren().clear();

        final Axis<Number> xAxis = _chart.getXAxis();
        final Axis<Number> yAxis = _chart.getYAxis();

        /* For each annotation, add a circle indicating the position and the custom node right next to it */
        for (ChartAnnotationNode annotation : _annotationNodes) {
            final double x = xAxis.localToParent(xAxis.getDisplayPosition(annotation.getX()), 0).getX() + _chart.getPadding().getLeft();
            final double y = yAxis.localToParent(0,yAxis.getDisplayPosition(annotation.getY())).getY() + _chart.getPadding().getTop();

            final Circle indicator = new Circle(3);
            indicator.setStroke(Color.BLUEVIOLET);
            indicator.setCenterX(x);
            indicator.setCenterY(y);

            getChildren().add(indicator);

            final Node node = annotation.getNode();
            getChildren().add(node);
            node.relocate(x + 10, y - node.prefHeight(Integer.MAX_VALUE) / 2);
            node.autosize();
        }
    }

    /**
     * Add a new annotation for the given display coordinate.
     */
    private void addAnnotation(final double displayX, final double displayY){
        final Axis<Number> xAxis = _chart.getXAxis();
        final Axis<Number> yAxis = _chart.getYAxis();

        final double x = (xAxis.getValueForDisplay(xAxis.parentToLocal(displayX, 0).getX() - _chart.getPadding().getLeft())).doubleValue();
        final double y = (yAxis.getValueForDisplay(yAxis.parentToLocal(0, displayY).getY() - _chart.getPadding().getTop())).doubleValue();

        if (xAxis.isValueOnAxis(x) && yAxis.isValueOnAxis(y))
            _annotationNodes.add(new ChartAnnotationNode(new Label("Annotation "+System.currentTimeMillis()), x, y));
    }
}

棘手的部分是视图和显示器之间的坐标转换。 要获取给定值的显示位置,你可以调用Axis#getDisplayPosition(...)但坐标返回将在轴坐标空间。 要将呼叫Axis#localToParent转换成图表的坐标空间这一点。 通常情况下,你希望能够只使用这些坐标,但图中有5个像素,由于某种原因将无法正确翻译默认填充。

这里有一个小的测试应用程序把他们放在一起:

public class SampleApp extends Application {
    @Override
    public void start(final Stage stage) throws Exception {
        final SampleChart chart = new SampleChart();

        final ChartAnnotationOverlay overlay = new ChartAnnotationOverlay(chart);

        final StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(chart, overlay);

        final Scene scene = new Scene(stackPane);
        stage.setScene(scene);
        stage.setWidth(800);
        stage.setHeight(600);
        stage.show();
    }

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

现在,您已经覆盖代码+翻译背后坐标,拖动节点应该是简单以及想法。 当一个注释的节点被拖动,获得它的显示位置,加上拖三角洲,将其转换为值,并将其应用到注释实例。

希望这使事情变得更清晰一点。



文章来源: JavaFx 2.x: How to write text on a chart?
标签: text javafx-2