与JPanel的麻烦

时间:2013-10-08 10:19:12

标签: java swing jpanel paintcomponent

我试图做一个简单的代码,使我的矩形更大。所以,我决定做一个线程,这将更新矩形的widght,它看起来像这样:

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();
}

}

1 个答案:

答案 0 :(得分:3)

在调试器中它看起来很好,宽度完全改变了它的数字。所以,我做错了,伙计们?

  • Swing GUI中的所有事件必须在EDT上完成,更多信息请参阅Concurency in Swing

  • MLP.repaint();无法在Java7中通知EDT

  • 使用Swing Timer代替普通Thread

  • getPreferrredSize

  • 中覆盖JPanel的{​​{1}}
  • 更好的帮助sooent发布SSCCE,简短,可运行,可编辑


修改

  • 不要在class ObjRectangle extends JPanel implements GraphicObject {中呼叫repaint();,因为,paintComponent()可以再次从其自身初始化,它可以创建无限的,无法管理的循环,为任务管理器添加