Java 如何在可滚动的JFrame中打印所有swing组件?

Java 如何在可滚动的JFrame中打印所有swing组件?,java,swing,Java,Swing,我正在尝试打印一个表单,该表单由可滚动JFrame中的swing组件组成。我已经尝试了下面的代码来做这件事,但我得到的打印只是当前窗口中的滚动区域。我需要打印整页 代码: 我还需要隐藏一些按钮和文本字段,以防打印。(例如:“打印”按钮) 任何帮助都将不胜感激。而不是这个.paint(gg)调用组件滚动窗格.paint(gg)。最好调用printAll(gg)如果尝试在图像上绘制jScrollPane,每次都会失败,只打印可见部分。为了解决这个问题,您需要绘制jScrollPane的内容,理想情况

我正在尝试打印一个表单,该表单由可滚动
JFrame
中的swing组件组成。我已经尝试了下面的代码来做这件事,但我得到的打印只是当前窗口中的滚动区域。我需要打印整页

代码:

我还需要隐藏一些按钮和文本字段,以防打印。(例如:“打印”按钮)
任何帮助都将不胜感激。

而不是
这个.paint(gg)调用
组件滚动窗格.paint(gg)。最好调用
printAll(gg)

如果尝试在图像上绘制jScrollPane,每次都会失败,只打印可见部分。为了解决这个问题,您需要绘制jScrollPane的内容,理想情况下,您将在jScrollPane中有一个jLayer、jPanel或其他容器,并且可以直接将其绘制到如下图像:

Form (jPanel top container)
 -> jScrollPane
     -> jLayer/jPanel/container
         -> Contents (tables, buttons etc)  
我不会给你关于如何用整个滚动窗格打印整个表单的代码,这需要一些数学知识和更多的代码,但为了让你开始,这里有一个示例方法,它将把一个jLayer的内容绘制到一个缓冲图像中,而不管它是否在jScrollPane中不可见,然后将该图像保存到文件中:(我不会涉及印刷这一问题)


最好的选择是使用
paint()将窗格内容绘制到缓冲图像
,然后打印出缓冲的图像。如果您能提供要添加的代码行,这将是一个很大的帮助。我是java新手,无法理解您给出的解决方案。感谢您必须用覆盖
paintComponent
:分配
BufferedImage
它的大小(这就是为什么不替换内容窗格)并调用
super.paintComponent(…)
两次:一次使用相同的参数,一次使用
buffereImage#createGraphics()
。谢谢。我尝试调用printAll(gg);而不是这个.paint(gg);。但仍然只有滚动区域(窗口中可见的内容)已打印。您可能在错误的容器上调用print。使用“this.paint(gg)”它将只打印滚动窗格内可行的部分图层。您需要在滚动窗格内的容器上调用print。该容器通常是
jPanel
jLayeredPane
,并且可以这样打印:
jPanel.paint(gg);
jLayeredPane.paint(gg)
。您还需要将
这个.getHeight/Width()
替换为
jPanel/jLayeredPane.getHeight/Width()
,否则它仍然只打印滚动窗格的可行大小。有关更多帮助,请发布GUI创建代码,以便我们可以看到它们是如何组合在一起的。
Form (jPanel top container)
 -> jScrollPane
     -> jLayer/jPanel/container
         -> Contents (tables, buttons etc)  
private void button4ActionPerformed() {
    try
    {
        //get height/width from the jLayeredPane or jPanel inside the scroll pane
        int imageHeight = jLayeredPane.getHeight();
        int imageWidth = jLayeredPane.getWidth();

        //Draw contents of the jLayeredPane or jPanel inside the scroll pane (but not the scroll pane itself)
        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);  
        Graphics2D gg = image.createGraphics();  
        jLayeredPane.paint(gg);

        //The "image" now has jLayers contents
        //Insert your code here to scale and print the image here
        //Some Code
        //In my example I have chosen to save the image to file with no scaling
        ImageIO.write(canvas, "png", new File("C:\\out.png"));
        //Some Code

        System.out.println("Done");
    }
    catch (IOException ex)
    {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}