作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想创建一条线,并在 2 秒后断开另一条线,依此类推。如果我画一条线并使用 Thread.sleep() 暂停程序执行,然后再次在 PaintComponent() 方法中画一条线,那么首先会发生的情况是程序停止 2 秒,然后两条线同时绘制。如何克服这个问题?
最佳答案
这确实是常见的要求和问题。您应该首先查看 Concurrency in Swing和 How to use Swing Timers有关如何解决您的基本问题的一些基本信息。
您还应该看看Painting in AWT and Swing和 Performing Custom Painting有关 Swing 中绘画工作原理的更多信息
您想要关注的核心设计选择是:
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/
我是一名优秀的程序员,十分优秀!