本文介绍了折线图上的JavaFX Adding Context菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的折线图上单击鼠标右键添加一个上下文菜单.基本上是为了调整图表大小.有什么办法可以实现?
I want to add a context menu on right click of my Line Chart.Its basically for re-sizing the chart.Is there any way i can achieve this?
推荐答案
下面是一个代码片段,当右键单击折线图时,可在折线图上显示调整大小的上下文菜单.
Here is a code snippet to bring up a resizing context menu on a line chart when the line chart is right clicked.
final MenuItem resizeItem = new MenuItem("Resize");
resizeItem.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent event) {
System.out.println("Resize requested");
}
});
final ContextMenu menu = new ContextMenu(
resizeItem
);
lineChart.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent event) {
if (MouseButton.SECONDARY.equals(event.getButton())) {
menu.show(stage, event.getScreenX(), event.getScreenY());
}
}
});
一些完整的示例代码:
Some complete sample code:
import javafx.application.Application;
import javafx.event.*;
import javafx.scene.Scene;
import javafx.scene.chart.*;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.stage.Stage;
public class LineChartWithContextMenu extends Application {
@Override public void start(final Stage stage) {
stage.setTitle("Line Chart Sample");
//defining the axes
final NumberAxis xAxis = new NumberAxis();
xAxis.setLabel("Number of Month");
final NumberAxis yAxis = new NumberAxis();
//creating the chart
final LineChart<Number,Number> lineChart =
new LineChart<>(xAxis,yAxis);
lineChart.setTitle("Stock Monitoring, 2010");
//defining a series
XYChart.Series series = new XYChart.Series();
series.setName("My portfolio");
//populating the series with data
series.getData().setAll(
new XYChart.Data(1, 23),
new XYChart.Data(2, 14),
new XYChart.Data(3, 15),
new XYChart.Data(4, 24),
new XYChart.Data(5, 34),
new XYChart.Data(6, 36),
new XYChart.Data(7, 22),
new XYChart.Data(8, 45),
new XYChart.Data(9, 43),
new XYChart.Data(10, 17),
new XYChart.Data(11, 29),
new XYChart.Data(12, 25)
);
lineChart.getData().add(series);
//adding a context menu item to the chart
final MenuItem resizeItem = new MenuItem("Resize");
resizeItem.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent event) {
System.out.println("Resize requested");
}
});
final ContextMenu menu = new ContextMenu(
resizeItem
);
lineChart.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent event) {
if (MouseButton.SECONDARY.equals(event.getButton())) {
menu.show(stage, event.getScreenX(), event.getScreenY());
}
}
});
stage.setScene(
new Scene(
lineChart,800,600
)
);
stage.show();
}
public static void main(String[] args) { launch(args); }
}
这篇关于折线图上的JavaFX Adding Context菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!