這是我的代碼。此代碼正在與1點擊延遲,但我不知道爲什麼。找不到任何理由爲什麼這樣工作。它可以是ArrayList或paintComponent方法的東西嗎?MouseListener無法識別第一次點擊
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();
}}
希望有任何幫助。
第一次點擊被檢測到,這是一個繪畫錯誤,而不是一個事件。 – DSquare
解決它的一些方法? –