В упражнении, при нажатии на прямоугольник, на границе прямоугольника отображается круг. Но когда правая кнопка мыши нажимается на круг, ее следует удалить. Я использовал ArrayList для хранения добавляемых кругов. Но как я узнаю, на какой клик? И затем для этого круга необходимо вызвать событие Click, чтобы удалить его.Событие Mouseclick на нескольких узлах
package sample;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.input.MouseButton;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Circle;
import javafx.scene.paint.Color;
import javafx.scene.control.Label;
import java.util.ArrayList;
import javafx.scene.text.Font;
import javafx.scene.layout.Pane;
public class Main extends Application {
private ArrayList <Circle> circles = new ArrayList<>();
private Rectangle rectangle = new Rectangle(200, 100, 1000, 600);
private Label[] label = new Label[2];
private int counter = 0;
private Pane pane = new Pane();
@Override
public void start(Stage stage) throws Exception {
rectangle.setFill(Color.WHITE);
rectangle.setStroke(Color.BLACK);
rectangle.setStrokeWidth(1);
rectangle.setOnMouseClicked(e -> {
if(e.getButton() == MouseButton.PRIMARY) {
// e.getX and e.getY will place the circle at the location of cursor click
AddCircle(e.getX(), e.getY());
}
});
// will format the labels to be added on the pane
formatLabels();
pane.getChildren().addAll(label[0], label[1], rectangle);
Scene scene = new Scene(pane, 1200, 650, Color.ANTIQUEWHITE);
stage.setScene(scene);
stage.setTitle("Add and Remove Circles");
stage.show();
}
public void AddCircle(double X, double Y) {
Circle circle = new Circle(X, Y, 10);
circle.setFill(Color.WHITE);
circle.setStroke(Color.BLACK);
circle.setStrokeWidth(1);
// adds circle object at value of counter
circles.add(counter, circle);
// setting id for object
circles.get(counter).setId("" + counter);
// adding circle from list into the pane
pane.getChildren().add(circles.get(counter));
// incrementing the counter after circle object is added
++counter;
}
private void formatLabels() {
label[0] = new Label();
label[0].setTranslateX(20);
label[0].setTranslateY(20);
label[0].setText("Press Left Mouse key to add a circle");
label[0].setFont(Font.font("Calibri", FontWeight.BLACK, FontPosture.REGULAR, 15));
label[1] = new Label();
label[1].setTranslateX(20);
label[1].setTranslateY(40);
label[1].setText("Press Right key on a circle to remove it");
label[1].setFont(Font.font("Calibri", FontWeight.BLACK, FontPosture.REGULAR, 15));
}
public static void main(String[] args)
{
launch(args);
}
}
Метод прямой прямой: перебирайте круги от самых новых до самых старых, и если вы найдете тот, который содержит точку щелчка, удалите его. – Thomas
Дублированный: http://stackoverflow.com/questions/31430767/add-remove-by-mouse-click –
Один вопрос: почему вы держите 'counter' и добавляете к этому индексу? Из вашего кода кажется, что 'круги.size()' будут делать то же самое (идентификатор будет 'круги.size() + 1', если вы установите его перед добавлением круга в список, хотя). – Thomas