gpt4 book ai didi

java - 通过鼠标单击而不是 setLocation 绘制每个矩形

转载 作者:行者123 更新时间:2023-12-01 20:18:40 24 4
gpt4 key购买 nike

目前,此代码段通过鼠标单击移动已在框架上绘制的当前矩形。该点击的坐标转到变量xy。无论单击框架上的何处,矩形都会移动到该位置。我希望它只是绘制一个新的矩形,因此例如当我在屏幕上随机单击 10 次时,将会出现 10 个矩形。你如何做到这一点?

public void moveRectangleTo(int x, int y)
{
box.setLocation(x, y);
repaint();
}

完整代码:矩形组件类

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;

public class RectangleComponent2 extends JComponent
{
private static final int BOX_X = 100;
private static final int BOX_Y = 100;
private static final int BOX_WIDTH = 20;
private static final int BOX_HEIGHT = 30;

private Rectangle box;

public RectangleComponent2()
{
box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT);
}

public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;

g2.draw(box);
}

public void moveRectangleTo(int x, int y)
{
box.setLocation(x, y);
repaint();
}
}

矩形框架类:

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;

public class RectangleFrame2 extends JFrame {
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 400;
private RectangleComponent2 scene;

class MousePressListener implements MouseListener {
public void mousePressed(MouseEvent event) {
int x = event.getX();
int y = event.getY();
scene.moveRectangleTo(x, y);
}
public void mouseReleased(MouseEvent event) {}
public void mouseClicked(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
}

public RectangleFrame2() {
scene = new RectangleComponent2();
add(scene);

setSize(FRAME_WIDTH, FRAME_HEIGHT);

MouseListener listener = new MousePressListener();
scene.addMouseListener(listener);
}
}

最佳答案

您需要保留一个盒子列表。

private List<Rectangle> boxes = new ArrayList<>();

单击鼠标时,不移动该框,而是添加一个新框:

public void addRectangleAt(int x, int y)
{
Rectangle boxNew = new Rectangle(x, y, BOX_WIDTH, BOX_HEIGHT);
boxes.add(boxNew);
repaint();
}

然后在您的 paintComponent() 方法中,迭代您的框列表并绘制每个框。

关于java - 通过鼠标单击而不是 setLocation 绘制每个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45268846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com