我应该自己实现Image
后台缓冲区还是已经制作了激活后台缓冲区的组件或选项?
我的目标是在窗口移动和隐藏/显示时保留图纸......
更新
我曾尝试使用 JPanel,因此我认为如果它有缓冲区,它应该可以工作,但失败了:
final JPanel panel = new JPanel();
panel.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
Graphics2D g2d = (Graphics2D) panel.getGraphics();
g2d.drawOval(e.getX()-50, e.getY()-50, 100, 100);
}
});
JFrame frame = new JFrame("JPanel Buffer Test");
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setBounds(100,100, 800, 600);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
这里的圆圈是在鼠标点击时绘制的,但如果窗口调整大小就会消失。因此,显然不存在缓冲区。
如果组件有缓冲区,我将能够在其上绘制一些东西,并且它会在调整大小时持续存在。
可能有一些方法可以访问JPanel
的缓冲区,除此之外getGraphics
?
更新 2
下面是我手动缓冲的方法。我的问题是它不是已经在图书馆完成了吗?示例在调整大小时重新采样缓冲区,这不是强制性的。
private BufferedImage bufferedImage = null;
@Override
protected void paintComponent(Graphics g) {
if( bufferedImage != null ) {
g.drawImage(bufferedImage, 0, 0, null);
}
}
@Override
public void setBounds(int x, int y, int width, int height) {
if( bufferedImage == null ) {
bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
else {
if( bufferedImage.getWidth() != width || bufferedImage.getHeight() != height ) {
BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
AffineTransform at = new AffineTransform();
at.scale((double)width/bufferedImage.getWidth(), (double)height/bufferedImage.getHeight());
AffineTransformOp scaleOp =
new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
bufferedImage = scaleOp.filter(bufferedImage, scaledImage);
}
}
super.setBounds(x, y, width, height);
}
public Graphics2D createImageGraphics() {
if( bufferedImage != null ) {
return bufferedImage.createGraphics();
}
else {
return null;
}
}