Java: переместить / перетащить фигуру с помощью мыши, если она реализована через другой класс? - PullRequest
0 голосов
/ 28 февраля 2020

Если я создал класс JFrame для создания объектов, который, в свою очередь, выполняется отдельным классом, как я могу реализовать методы для перемещения фигуры с помощью мыши (нажав на объект и перетащив его на экран) ?

Я создал этот класс для создания круга:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Circle extends JPanel {

    public Circle(Graphics g, int diameter, int x, int y){ // take an object from the graphics class and manipulate this object in our own drawing
        // draw a rectangle on the screen
        g.setColor(Color.RED); // change the color for the rectangle
        g.fillOval(x, y, diameter, diameter); // coordinate x, coordinate y, width, height
    }

}

И я создал этот класс для добавления объекта (вместе с 2 другими фигурами) на экран:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Graphics_class extends JPanel {

    // Use this method to paint a square, a circle and a triangle on the screen
    public void paintComponent(Graphics g){

        // Call the superclass and use its method for the drawing
        super.paintComponent(g);

        // set background color for the screen
        this.setBackground(Color.WHITE); // white background

        // Create a square
        Square S = new Square(g, 100, 100, 25, 25);

        // Create circle
        Circle C = new Circle(g, 100, 150+25, 25);

        // Create triangle
        Triangle T = new Triangle(g, 100, 100, 150+150+25, 25, true);


    }
}

Кроме того, я создал этот класс для хранения main:

import javax.swing.*;
public class Main{
        public static void main(String args[]){
            // Create a new JFrame object and set a title
            JFrame f = new JFrame("Title");
            // Set close method
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // Create graphic objects (a square, a circle and a triangle) by using the method paintComponent in this class
            Graphics_class Graphic_Objects = new Graphics_class();
             // Add this object list to the screen and visualize the results
            f.add(Graphic_Objects);
            f.setSize(500, 500);
            f.setVisible(true);
        }
    }

Как можно перетащить форму (например, круг) с помощью мыши?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...