Java - запросить алгоритмы для графических движений - PullRequest
0 голосов
/ 23 апреля 2020

Я занимаюсь графикой в ​​java с движением с использованием таймера. Я создал 2 графических c объекта и затем хочу изменить их вместе, как показано на рисунке ниже:

enter image description here

И это мой код:

 import java.awt.Color;
 import java.awt.Dimension;
 import java.awt.Font;
 import java.awt.Graphics;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import javax.swing.JFrame;
 import javax.swing.JPanel;
 import javax.swing.SwingUtilities;
 import javax.swing.Timer;

@SuppressWarnings("serial")
public class DrawingGraphicObject extends JFrame {

// Define named-constants
private static final int CANVAS_WIDTH = 640;
private static final int CANVAS_HEIGHT = 480;
private static final int UPDATE_PERIOD = 50; // milliseconds
private DrawCanvas canvas; // the drawing canvas (an inner class extends JPanel)

// Attributes of moving object
private int w = 150, h = 90; // width and height
private int gap = 20;
private int x1 = 100, y1 = 100; // top-left (x, y)
private int x2 = x1 + w + gap, y2 = y1;
// private int x2, y2;
private int xSpeed = 7, ySpeed = 9; // displacement per step in x, y

// Limited Points
private int limX1 = x1 + w + gap;
private int limY1 = y1 + h + gap;
private int limX2 = x2 - gap - w;
private int limY2 = y2 - gap - h;

// Variables which is used to save the starting position 
private static final int y1Temp = 100;
private static final int y2Temp = 100;

// Constructor to setup the GUI components and event handlers
public DrawingGraphicObject() {
    canvas = new DrawCanvas();
    canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
    this.setContentPane(canvas);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.pack();
    this.setTitle("Bouncing Ball");
    this.setVisible(true);

    // Define an ActionListener to perform update at regular interval
    ActionListener updateTask = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            update(); // update the (x, y) position
            repaint(); // Refresh the JFrame, callback paintComponent()
        }
    };
    // Allocate a Timer to run updateTask's actionPerformed() after every delay msec
    new Timer(UPDATE_PERIOD, updateTask).start();
}

// Update the (x, y) position of the moving object
public void update() {
    y1 += ySpeed;
    if (y1 >= limY1) {
        y1 = limY1;
        x1 += xSpeed;
        if (x1 >= limX1) {
            x1 = limX1;
            if (y1 != y2Temp) {
                y1 -= ySpeed;
            }
        }
    }

    System.out.println("x1: " + x1 + " y1: " + y1 + " lim y1: " + limY1 + " y2Temp: " + y2Temp);

    y2 -= ySpeed;
    if (y2 <= limY2) {
        y2 = limY2;
        x2 -= xSpeed;
        if (x2 < limX2) {
            x2 = limX2;
            if (y2 != y1Temp) {
                y2 += ySpeed;
            }
        }
    }
    System.out.println("x2: " + x2 + " y2: " + y2 + " lim y2: " + limY2 + " y1Temp: " + y2Temp);
}

// Define inner class DrawCanvas, which is a JPanel used for custom drawing
private class DrawCanvas extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g); // paint parent's background
        setBackground(Color.BLACK);
        Font font = new Font("Arial", Font.BOLD, 20);

        g.setColor(Color.BLUE);
        g.fillRoundRect(x1, y1, w, h, 20, 20);
        g.setColor(Color.RED);
        g.drawString("1", x1 + w / 2, y1 + h / 2);
        g.setFont(font);

        g.setColor(Color.WHITE);
        g.fillRoundRect(x2, y2, w, h, 20, 20);
        g.setColor(Color.BLACK);
        g.drawString("2", x2 + w / 2, y2 + h / 2);
        g.setFont(font);
    }
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new DrawingGraphicObject();
        }
    });
}
}

Это не сработало правильно, то есть объект-1 двигался вниз, двигался вправо, а затем просто короткое движение вверх. Я думаю, что проблема в методе update (), я пытался изменить другие алгоритмы, но это невозможно. Пожалуйста, помогите всем. Спасибо.

...