我正在尝试做一个简单的代码来使我的矩形更大。所以,我决定做一个线程,它会更新矩形的宽度,它看起来像这样:
class CoolThread extends Thread {
MyPanel MLP;
public CoolThread(MyPanel Panel1) {
MLP = Panel1;
}
@Override
public void run() {
super.run();
while (true) {
for (int i = 0; i < MLP.arrForRect.size() - 1; i++) {
MLP.arrForRect.get(i).animation();
MLP.repaint();
}}}}
在调试器中它看起来很好,宽度完美地改变了它的数字。那么,我做错了什么,伙计们?现在我的问题是当我点击窗口时奇怪的输入延迟。针对 Ctrl+c、CTRL+v 编译进行了编辑。
public class PaintWindow {
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 mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println(getMousePosition());
animTimer=new Timer(100,taskPerformer);
animTimer.start();
mousePos = getMousePosition();
ObjRect1 = new ObjRectangle();
arrForRect.add(ObjRect1);
repaint();
}
});
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
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 {
PaintWindow window1= new PaintWindow();
window1.createGUI();
}
}