简体   繁体   English

循环以在单击鼠标时重复操作

[英]Loop to repeat an action when the mouse is clicked

I am making a connect 4 game and I have that is on click as follows. 我正在制作一个连接4游戏,我点击如下。

    public void mouseClicked(MouseEvent e) {
    xPos = e.getX();
    yPos = e.getY();
    this.repaint();

    x = e.getX(); 
    if(x <= 400) { 
        x = x/48; 
        System.out.println("Column number " + x);
        positions[0][0]=1;
        Component board = e.getComponent();
    }
}

I then have a method that creates a red circle on the grid as follows 然后,我有一个方法,在网格上创建一个红色圆圈,如下所示

    public void fillCircle(Graphics g) {
    {
        g.setColor(Color.red);
        g.fillOval(xPos,yPos,40,40);
    }
}

However only one circle appears on click and when you re-click the circle is removed and is placed in the new position. 但是,单击时只显示一个圆圈,当您重新单击时,圆圈将被移除并放置在新位置。

I believe I need to include some kind of loop on the fill circle method so that it doesnt just get rid of the circle and put onew in the new location, but it leaves it there and puts a new circle in the new place? 我相信我需要在填充圆方法中包含某种循环,这样它才能摆脱圆圈并将onew放在新位置,但它会将它留在那里并在新位置放置一个新圆圈?

How would I do this? 我该怎么做?

You need to add the positions to an ArrayList or something because you're just overriding the variables xPos and yPos when you click. 您需要将位置添加到ArrayList或其他东西,因为您只是在单击时覆盖变量xPosyPos We can create a Position class to hold both x and y values so we only need one ArrayList . 我们可以创建一个Position类来保存x和y值,这样我们只需要一个ArrayList

ArrayList<Position> positions = new ArrayList<Position>();

public void mouseClicked(MouseEvent e) {
    positions.add(new Position(e.getX(), e.getY()));

    // ...
}

And the Position class Position

class Position {
    public int x;
    public int y;

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

Then draw all the circles in your function 然后绘制函数中的所有圆圈

public void fillCircle(Graphics g) {
{
    g.setColor(Color.red);
    for (int i = 0; i < positions.size(); i++)
        g.fillOval(positions.get(i).x, positions.get(i).y, 40, 40);
}

Update 更新

Include this at the very top of the file. 将其包含在文件的最顶部。

import java.util.ArrayList;

This will import the ArrayList library that you want to use. 这将导入您要使用的ArrayList库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM