gpt4 book ai didi

java - 随着时间的推移,一个一个地绘制形状,而不是一次性绘制所有形状

转载 作者:行者123 更新时间:2023-12-01 20:52:19 25 4
gpt4 key购买 nike

我想创建一条线,并在 2 秒后断开另一条线,依此类推。如果我画一条线并使用 Thread.sleep() 暂停程序执行,然后再次在 PaintComponent() 方法中画一条线,那么首先会发生的情况是程序停止 2 秒,然后两条线同时绘制。如何克服这个问题?

最佳答案

这确实是常见的要求和问题。您应该首先查看 Concurrency in SwingHow to use Swing Timers有关如何解决您的基本问题的一些基本信息。

您还应该看看Painting in AWT and SwingPerforming Custom Painting有关 Swing 中绘画工作原理的更多信息

您想要关注的核心设计选择是:

  1. 不要阻塞事件调度线程,这将阻止它绘制任何内容或响应新事件
  2. 不要在 EDT 上下文之外更新 UI
  3. 绘画应该是绘画状态。它不应该专注于尽可能做出逻辑决策,相反,它应该依赖一个或多个模型来为其提供绘制自身所需的信息
<小时/>
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private List<Shape> shapes;
private int yPos = 0;

public TestPane() {
shapes = new ArrayList<>(25);

Timer timer = new Timer(2000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
yPos += 10;
Line2D line = new Line2D.Double(0, yPos, getWidth(), yPos);
shapes.add(line);
repaint();
}
});
timer.setInitialDelay(2000);
timer.start();
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (Shape line : shapes) {
g2d.draw(line);
}
g2d.dispose();
}

}

}

关于java - 随着时间的推移,一个一个地绘制形状,而不是一次性绘制所有形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43032843/

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