我会设置一个固定的单元格大小,然后使用鼠标坐标进行猜测。我只是将它添加到现有示例中,我确信它不太正确,但它显示了这个想法。
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.converter.NumberStringConverter;
public class ChangePie extends Application {
@Override
public void start(Stage primaryStage) {
ObservableList<PieChart.Data> pieChartData
= FXCollections.observableArrayList(
new PieChart.Data("Grapefruit", 13),
new PieChart.Data("Oranges", 25),
new PieChart.Data("Plums", 10),
new PieChart.Data("Pears", 22),
new PieChart.Data("Apples", 30));
final PieChart chart = new PieChart(pieChartData);
chart.setTitle("Imported Fruits");
final TableView<PieChart.Data> tv = new TableView(pieChartData);
tv.setEditable(true);
tv.setFixedCellSize(40);
tv.addEventHandler(MouseEvent.ANY, (MouseEvent evt) -> {
double y = 0;
int idx1 = 0, idx2 = 0;
if (evt.getEventType() == MouseEvent.MOUSE_PRESSED) {
y = evt.getY();
idx1 = tv.getSelectionModel().getSelectedIndex();
} else if (evt.getEventType() == MouseEvent.MOUSE_RELEASED) {
idx2 = (int) Math.round((evt.getY() - y) / 40);
System.out.println("insert at " + idx2);
if (idx2 > 0) {
chart.setData(null);
PieChart.Data removed = pieChartData.remove(idx1);
pieChartData.add(Math.min(idx2, pieChartData.size() - 1), removed);
}
}
});
TableColumn tc1 = new TableColumn("Name");
tc1.setPrefWidth(100);
tc1.setCellValueFactory(new PropertyValueFactory("name"));
tc1.setCellFactory(TextFieldTableCell.forTableColumn());
TableColumn tc2 = new TableColumn("Data");
tc2.setPrefWidth(100);
tc2.setCellValueFactory(new PropertyValueFactory("pieValue"));
tc2.setCellFactory(TextFieldTableCell.forTableColumn(new NumberStringConverter()));
tv.getColumns().addAll(tc1, tc2);
Scene scene = new Scene(new VBox(chart, tv));
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}