gpt4 book ai didi

java - MouseListener 无法识别第一次点击

转载 作者:行者123 更新时间:2023-11-29 05:36:46 24 4
gpt4 key购买 nike

这是我的代码。此代码具有 1 次点击延迟,但我不知道为什么。找不到它以这种方式工作的任何原因。它可以是 ArrayList 或 paintComponent 方法吗?

 import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

class PaintWindow {
public void createGUI() {
JFrame f = new JFrame("My Canvas");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.setSize(800, 400);
f.setResizable(false);
f.setVisible(true);
f.setLocationRelativeTo(null);
}

}
class MyPanel extends JPanel {
public Point mousePos;
Timer animTimer;
ArrayList<ObjRectangle> arrForRect = new ArrayList<ObjRectangle>();
ObjRectangle ObjRect1;

public MyPanel() {
final ActionListener taskPerformer=new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i=0;i<arrForRect.size()-1;i++){
arrForRect.get(i).animation();
repaint();
}
}
};

addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
System.out.println(getMousePosition());
animTimer=new Timer(100,taskPerformer);
animTimer.start();
mousePos = getMousePosition();
ObjRect1 = new ObjRectangle();
arrForRect.add(ObjRect1);
repaint();
}
});


}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(arrForRect.size()==0){
return;
}
arrForRect.get(arrForRect.size() - 1).drawObject(mousePos);
for (int i = 0; i < arrForRect.size() - 1; i++) {
arrForRect.get(i).paintSquare(g);
}
} }

class ObjRectangle extends JPanel {
int x, y = 0;
int width = 50;
int height = 20;


public void drawObject(Point coordinates) {
this.x = coordinates.x;
this.y = coordinates.y;
}

public void animation() {
width++;
}

public void paintSquare(Graphics g) {
g.setColor(Color.BLACK);
g.drawRect(x, y, width, height);
}
}

public class MainClass {
public static void main(String[] args) {
PaintWindow kazo=new PaintWindow();
kazo.createGUI();
}}

非常感谢任何帮助。

最佳答案

如您的 println 所示,点击检测正常。愚蠢的错误在这里:

for (int i=0;i<arrForRect.size()-1;i++){
arrForRect.get(i).animation();
repaint();
}

arrForRect.size()-1当然应该是arrForRect.size()

干杯。

关于java - MouseListener 无法识别第一次点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19254718/

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