gpt4 book ai didi

java - Java SWING 程序中的事件调度线程

转载 作者:行者123 更新时间:2023-11-30 07:38:39 25 4
gpt4 key购买 nike

我完全是Java新手。我想制作一个动画。但我没有成功。 mouseClicked() 将在事件调度线程中执行。为什么不起作用?事件派发会不会被其他线程占用,其他什么线程?

public class DemoThreadGUI {

public static void main(String [] args) {
DemoThreadGUI app = new DemoThreadGUI();
app.go();
}

public void go() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
generateGUI();
}
});
}
public void generateGUI() {
JFrame frame = new JFrame("Demo");
frame.add(new MyPanel());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

class MyPanel extends JPanel implements MouseListener {
private int x,y;
private int r;
public MyPanel() {
this.setPreferredSize(new Dimension(100,100));
this.addMouseListener(this);
x = 50;
y = 50;
r = 25;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(x-r,y-r,r*2,r*2);
}

public void mouseClicked(MouseEvent event) {
int targetX = event.getX();
int targetY = event.getY();
for(int i=0;i<10;++i) {
x = (x+targetX)/2;
y = (y+targetY)/2;
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) { }
}
}

public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mousePressed(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}

}

}

最佳答案

在 mouseClicked() 中启动一个新线程并将代码放入线程中

       for(int i=0;i<10;++i) {
x = (x+targetX)/2;
y = (y+targetY)/2;
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) { }
}

repaint() 调用应包装到 SwingUtilities.invokeAndWait() 中以将控制权传递给 EDT

关于java - Java SWING 程序中的事件调度线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35014146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com