如何在不重置的情况下绘制多个对象 Java

How to paint multiple objects without reset Java

我正在尝试绘制单个单元格 (20x20px),因为我正在开始康威生活游戏。当我在屏幕上单击时,我会绘制一个单元格,或者根据数组中单元格的状态将其删除。然而,这是有效的,在任何给定时刻屏幕上只能出现一个单元格,我不确定为什么如果我单击屏幕的不同部分,单元格数组中的位置会发生变化。

主要代码



import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferStrategy;
import java.util.ArrayList;
import java.util.Iterator;

public class mainApplication extends JFrame implements Runnable, MouseListener {


    private static final Dimension windowsize = new Dimension(80, 600);
    private BufferStrategy strategy;
    private static boolean isGraphicsInitialised = false;
    private static int rows = 40;
    private static int columns = 40;
    private static int height = windowsize.height;
    private static int width = windowsize.width;
    private static ArrayList<Cell> cellsList = new ArrayList<>();
    private int xArrayElement,yArrayElement, xPosition, yPosition;
    private static boolean gameState[][] = new boolean[rows][columns];


    public mainApplication() {


        System.out.println(System.getProperty("user.dir"));

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();

        int x = screensize.width / 2 - width / 2;
        int y = screensize.height / 2 - height / 2;

        setBounds(x, y, screensize.width, screensize.height);

        setVisible(true);

        createBufferStrategy(2);

        strategy = getBufferStrategy();

        isGraphicsInitialised = true;

       // MouseEvent mouseEvent = new MouseEvent();
        addMouseListener(this);
       // addMouseMotionListener(MouseEvent);

        Thread t = new Thread(this);

        t.start();

    }


    public void mousePressed(MouseEvent e) { }

    public void mouseReleased(MouseEvent e) { }

    public void mouseEntered(MouseEvent e) { }

    public void mouseExited(MouseEvent e) { }

    public void mouseClicked(MouseEvent e) {

           int x = e.getX();
           int y = e.getY();

            xArrayElement = (x/20);
            yArrayElement = (y/20);

            xPosition = x - (x % 20);
            yPosition = y - (y % 20);

//      cellList.removeIf(cell -> cell.contains(xPosition, yPosition));

        Iterator<Cell> iterator = cellsList.iterator();

        if (e.getButton() == MouseEvent.BUTTON3) {
            while (iterator.hasNext()) {
                if (iterator.next().contains(xPosition, yPosition)) {
                    iterator.remove();
                }
            }
        }

        else{

            cellsList.add(new Cell(xPosition, yPosition));
        }


    }

    @Override
    public void run() {
            while (true) {

                try { //threads entry point
                    Thread.sleep(20); //forces us to  catch exception
                }

                catch (InterruptedException e) {
                }
            }
        }


    public void paint(Graphics g) {

        if (isGraphicsInitialised) {
            g = strategy.getDrawGraphics();
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 800, 800);

            if(cellsList != null) {

                for (Cell cell : cellsList) {
                    cell.paint(g);
                    System.out.println("test");
                }
            }

        this.repaint();
        strategy.show();
        }
    }

    public static void main(String[]args){

        mainApplication test = new mainApplication();

    }
}

单元格CLASS

import java.awt.*;

public class Cell {

    int x;
    int y;


    public Cell(int x, int y){
        this.x = x;
        this.y = y;
    }


    public boolean contains(int xx, int yy) {

        return xx >= x && yy >= y && xx <= x + 20 && yy <= y + 20;
    }

    public void paint(Graphics g){
        g.setColor(Color.white);
        g.fillRect(x, y, 20,20);
    }
}

这里有一个例子供您检查。它使用鼠标添加或删除彩色方块。要添加正方形,请将鼠标放在面板中的某个位置并单击左键。要删除,请将鼠标放在正方形上并单击右键。请注意,每次单击鼠标,我都会修改列表并重新绘制整个列表。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class AddingSquares {
    JFrame f = new JFrame("Demo");

    public AddingSquares() {
        f.add(new MyPanel(500, 500));
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // compress various components and invoke any 
        // layout managers.
        f.pack();
        // center on screen
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        // start on the EDT
        SwingUtilities.invokeLater(() -> new AddingSquares());
    }

}

class MyPanel extends JPanel {

    public MyPanel(int w, int h) {
        // the following statement won't work unless you
        // do super.paintComponent().
        setBackground(Color.white);
        setPreferredSize(new Dimension(w, h));
        addMouseListener(new MyMouseListener());
    }

    List<Square> list = new ArrayList<>();
    int side = 20;

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // I prefer graphics2D as it has additional features.
        // Not using any here though.
        Graphics2D g2d = (Graphics2D) g.create();
        if (list != null) {
            for (Square sq : list) {
                sq.draw(g2d);
            }
        }

        g2d.dispose();
    }

    private class MyMouseListener extends MouseAdapter {
        public void mouseClicked(MouseEvent me) {
            int x = me.getX();
            int y = me.getY();
            // right mouse button removes square
            if (me.getButton() == MouseEvent.BUTTON3) {
                Iterator<Square> it = list.iterator();
                while (it.hasNext()) {
                    if (it.next().contains(x, y)) {
                        it.remove();
                        break;
                    }
                }
            } else {
                // I want the square drawn with the mouse at the center, not upper left
                // corner, so I adjust the coordinates
                list.add(new Square(x - side/2, y - side/2));
            }
            repaint();
        }
    }
    // this could be an external class but it is convenient for this demo.
    private class Square {
        int x;
        int y;
        Color color = Color.blue;

        public Square(int x, int y) {
            this.x = x;
            this.y = y;
        }

        // used to find the right square to remove
        public boolean contains(int xx, int yy) {
            return xx >= x && yy >= y && xx <= x + side
                    && yy <= y + side;
        }

        public void draw(Graphics2D g2d) {
            g2d.setColor(color);
            g2d.fillRect(x, y, side, side);
        }
    }
}