MouseListener无法识别第一次单击

时间:2013-10-08 17:47:37

标签: java swing mouseevent paintcomponent

这是我的代码。此代码使用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();
}}

感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

如您的println所示,点击检测很好。愚蠢的虫子在这里:

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

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

干杯。