我正在尝试将 JPanel 图片写入 BufferedImage(稍后转换为渲染图像)。由于某种原因,我在 AWT-EventQueue-0 线程中遇到堆栈溢出错误,并且不确定是否有我忽略的原因。
有问题的代码:
public BufferedImage createImage() {
int w = getWidth();
int h = getHeight();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
cp.paint(bi.getGraphics());
//debug script
File outputfile = new File("image"+index+".jpg");
try {
ImageIO.write(bi, "jpg", outputfile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
index++;
return bi;
}
JPanel 绘画组件
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
r = new Random(System.nanoTime());
int maxSize = 100;
int randX = r.nextInt(getWidth());
int randY = r.nextInt(getHeight());
int randWidth = r.nextInt(maxSize);
int randHeight = r.nextInt(maxSize);
Color color = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
Graphics2D g2d = (Graphics2D) g;
ovals.add(new MyCircles(randX, randY, randWidth, randHeight, color));
for (MyCircles c : ovals) {
c.paint(g2d);
}
g2d.setColor(getForeground());
repaint();
double current = ImageComparator.calcDistance((RenderedImage)createImage());
//debugging script
System.out.println("Current: " + current);
System.out.println("Previous" + previous);
if(current > previous) {
ovals.remove(ovals.size()-1);
}
else {
previous = current;
}
}
任何有关如何修改此问题的见解将不胜感激!
最佳答案
删除 paintComponent
中对 repaint
的调用,这会导致该方法被无限次调用
关于java - 将 Jpanel 写入缓冲图像堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30357381/