我尝试从JScrollpane的内容创建缓冲图像。 Jscrollpane尺寸为250x200。内容溢出,只有可见部分被捕获在图像中。我正在使用Java图形2D。
有没有办法捕获滚动页面的完整内容?
答案 0 :(得分:2)
只需将内容绘制到BufferedImage,而不是滚动窗格。
例如:
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
final Image image =
new ImageIcon("stackoverflow.png").getImage();
JPanel imagePanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(this),
image.getHeight(this));
}
};
JScrollPane pane = new JScrollPane(imagePanel);
pane.setPreferredSize(new Dimension(200, 200));
JOptionPane.showMessageDialog(null, pane);
BufferedImage newImage = getImageFromComponent(imagePanel);
JLabel label = new JLabel(new ImageIcon(newImage));
JOptionPane.showMessageDialog(null, label);
}
});
}
private static BufferedImage getImageFromComponent(Component component) {
BufferedImage img = new BufferedImage(
component.getWidth(), component.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = img.createGraphics();
component.paint(g);
g.setFont(new Font("impact", Font.PLAIN, 30));
g.drawString("Image of Panel", 40, 50);
g.dispose();
return img;
}
}
首先,面板放在滚动窗格内。
当我们关闭它时,面板的内容将被绘制到BufferedImage,并添加到标签中。