[英]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.