编辑为更好的例子
本质上,我们可以使用RepaintManager
来跟踪/更新我们每毫秒更改的几个像素。肮脏的区域会累积,直到油漆真正能够发生。当绘制发生时,它使用paintImmediately(int x, int y, int w, int h)
函数(除非整个组件是脏的)——所以我们只更新图像的一小部分就可以了。希望示例代码不依赖于操作系统 - 如果它不适合您,请告诉我。
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class UpdatePane extends JPanel{
final int MAX = 1024;
//The repaint manager in charge of determining dirty pixels
RepaintManager paintManager = RepaintManager.currentManager(this);
//Master image
BufferedImage img = new BufferedImage(MAX, MAX, BufferedImage.TYPE_INT_RGB);
@Override
public void paintComponent(Graphics g){
g.drawImage(img, 0, 0, null);
}
public void paintImmediately(int x, int y, int w, int h){
BufferedImage img2 = img.getSubimage(x, y, w, h);
getGraphics().drawImage(img2, x, y, null);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
final UpdatePane outside = new UpdatePane();
outside.setPreferredSize(new Dimension(1024,1024));
JFrame frame = new JFrame();
frame.add(outside);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
outside.new Worker().execute();
}
});
}
//Goes through updating pixels (like your application would)
public class Worker extends SwingWorker<Integer, Integer>{
int currentColor = Color.black.getRGB();
public int x = 0;
public int y = 0;
@Override
protected Integer doInBackground() throws Exception {
while(true){
if(x < MAX-1){
x++;
} else if(x >= MAX-1 && y < MAX-1){
y++;
x = 0;
} else{
y = 0;
x = 0;
}
if(currentColor < 256){
currentColor++;
} else{
currentColor = 0;
}
img.setRGB(x, y, currentColor);
//Tells which portion needs to be repainted [will call paintImmediately(int x, int y, int w, int h)]
paintManager.addDirtyRegion(UpdatePane.this, x, y, 1, 1);
Thread.sleep(1);
}
}
}
}