簡體   English   中英

與JPanel的麻煩

[英]Troubles with JPanel

我試圖做一個簡單的代碼,使我的矩形更大。 所以,我決定做一個線程,這將更新矩形的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();
}

}

在調試器中它看起來很好,寬度完美地改變了它的數字。 所以,我做錯了,伙計們?

  • Swing GUI中的所有事件必須在EDT上完成,更多在Swing中的Concurency中讀取

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

  • 使用Swing Timer而不是普通的Thread

  • 覆蓋class ObjRectangle extends JPanel implements GraphicObject { JPanel getPreferrredSize class ObjRectangle extends JPanel implements GraphicObject {

  • 為了更好的幫助sooent發布SSCCE ,簡短,可運行,可編譯


編輯

  • 不要調用repaint(); paintComponent() ,因為, paintComponent()可以從自身初始化,它可以創建無窮無盡的循環,任務管理器的addept

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM