这是我的代码。此代码使用 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();
}}
将不胜感激任何帮助。