Как сделать так, чтобы рамка перекрашивалась до закрытия окна? - PullRequest
2 голосов
/ 05 марта 2020

В настоящее время я делаю куб (рисуя с помощью point2d и line2d для создания фигуры), перемещаясь по рамке, как в pong или в пузырьках заставки окна. Я могу напечатать куб на рамке, но не понимаю, как заставить его двигаться после первой печати. Я хочу использовать слушатель действия таймера, чтобы заставить шар двигаться.

Просмотр

import javax.swing.JFrame;
public class CubeBounceViewer {

    public static void main(String[] agrs) {
        JFrame frame = new JFrame();

        frame.setTitle("Cube Bounce");
        frame.setSize(1280,720);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        CubeBounceComponent component = new CubeBounceComponent();
        frame.add(component);
    }
}

Компонент

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComponent;
import javax.swing.Timer;

public class CubeBounceComponent extends JComponent{

    public void paintComponent(Graphics g) {

        Graphics2D g2 = (Graphics2D) g;

        //Creates a object list with size equal to value of instance
        Cube cube = new Cube();

        class TimerListener implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                cube.move();
            }
        }

        ActionListener listener = new TimerListener();

        final int DELAY = 100;
        Timer t = new Timer(DELAY, listener);
        t.start();

        cube.draw(g2);
        cube.move();
        if (cube.getX()>=1265 || cube.getX()<=15 && cube.getY()<=15 || cube.getY()>=705) {
            cube.changeDirection(-1, -1);
        } else if(cube.getX()>=1265 || cube.getX()<=15) {
            cube.changeDirection(-1, 1);
        } if (cube.getY()<=15 || cube.getY()>=705) {
            cube.changeDirection(1,-1);
        }

    }
}

Куб

import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

public class Cube {
    private int centerX,centerY,directionX, directionY;

    public Cube() {
        centerX=640;
        centerY=360;
        directionX=1;
        directionY=1;
    }

    public void draw(Graphics2D g2) {
        Point2D.Double backTopLeft = new Point2D.Double(centerX-10,centerY-15);
        Point2D.Double backTopRight = new Point2D.Double(centerX+15,centerY-15);
        Point2D.Double backBottomLeft = new Point2D.Double(centerX-10,centerY+10);
        Point2D.Double backBottomRight = new Point2D.Double(centerX+15,centerY+10);
        Point2D.Double frontTopLeft = new Point2D.Double(centerX-15,centerY-10);
        Point2D.Double frontTopRight = new Point2D.Double(centerX+10,centerY-10);
        Point2D.Double frontBottomLeft = new Point2D.Double(centerX-15,centerY+15);
        Point2D.Double frontBottomRight = new Point2D.Double(centerX+10,centerY+15);

        Line2D.Double backTop = new Line2D.Double(backTopLeft,backTopRight);
        Line2D.Double backRight = new Line2D.Double(backTopRight,backBottomRight);
        Line2D.Double backLeft = new Line2D.Double(backTopLeft,backBottomLeft);
        Line2D.Double backBottom = new Line2D.Double(backBottomLeft,backBottomRight);
        Line2D.Double frontTop = new Line2D.Double(frontTopLeft,frontTopRight);
        Line2D.Double frontRight = new Line2D.Double(frontTopRight,frontBottomRight);
        Line2D.Double frontLeft = new Line2D.Double(frontTopLeft,frontBottomLeft);
        Line2D.Double frontBottom = new Line2D.Double(frontBottomLeft,frontBottomRight);
        Line2D.Double topLeft = new Line2D.Double(backTopLeft,frontTopLeft);
        Line2D.Double topRight = new Line2D.Double(backTopRight,frontTopRight);
        Line2D.Double bottomLeft = new Line2D.Double(backBottomLeft,frontBottomLeft);
        Line2D.Double bottomRight = new Line2D.Double(backBottomRight,frontBottomRight);

         g2.draw(backTop);
         g2.draw(backRight);
         g2.draw(backLeft);
         g2.draw(backBottom);
         g2.draw(frontTop);
         g2.draw(frontRight);
         g2.draw(frontLeft);
         g2.draw(frontBottom);
         g2.draw(topLeft); 
         g2.draw(topRight);
         g2.draw(bottomLeft);
         g2.draw(bottomRight); 
    }

    public void changeDirection(int x, int y) {
        directionX*=x;
        directionY*=y;
    }
    public void move() {
        centerX+=1*directionX;
        centerY+=1*directionY;
    }

    public int getX() {
        return centerX;
    }
    public int getY() {
        return centerY;
    }
}

Любая помощь с благодарностью! Спасибо.

Ответы [ 2 ]

0 голосов
/ 05 марта 2020

Сначала сделайте куб членом вашего класса, а не локальной переменной. Во-вторых, удалите все движущиеся логи c из вашего компонента краски. Третий Запрос перекрасить после того, как вы обновили позицию кубов.

Cube cube = new Cube();

public void updatePosition(){


    cube.move();
    if (cube.getX()>=1265 || cube.getX()<=15 && cube.getY()<=15 || cube.getY()>=705) {
        cube.changeDirection(-1, -1);
    } else if(cube.getX()>=1265 || cube.getX()<=15) {
        cube.changeDirection(-1, 1);
    } if (cube.getY()<=15 || cube.getY()>=705) {
        cube.changeDirection(1,-1);
    }
    repaint();
}

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    cube.draw(g2);
}

Теперь у вас есть куб, который может изменить положение. У вас также есть способ изменить позицию. Поэтому в вашем основном методе создайте таймер, который вызывает метод обновления.

    class TimerListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            component.updatePosition();
        }
    }

    ActionListener listener = new TimerListener();

    final int DELAY = 100;
    Timer t = new Timer(DELAY, listener);
    t.start();

Обратите внимание, что вы можете использовать лямбда-выражения, чтобы сделать это немного более кратким, и не нуждаться в именованном классе TimerListener.

Timer t = new Timer(DELAY, evt->component.updatePosition() )
0 голосов
/ 05 марта 2020

Это выстрел в темноте, но вы пытались вставить свой код в:

While (true) {}
...