WerWolf
WerWolf

Reputation: 124

Paint hidden Java swing component

I've tried to paint component to PDF. I've got itextpdf 4.2 and everything works perfectly. But this works only if I make visible the frame that I've tried to render.

The similar question that I've found is How to paint an invisible JFrame elsewhere? that has the same issue, but the solution wasn't provided in answer.

A little of code. I've created a JFrame and insert main view that I want to render.

JFrame jframe = new ShowingFrame();
jframe.setPreferredSize(new Dimension(PDFHelper.getOriginalWidth().intValue(), PDFHelper.getOriginalHeight().intValue()));
jframe.setMinimumSize(new Dimension(PDFHelper.getOriginalWidth().intValue(), PDFHelper.getOriginalHeight().intValue()));
jframe.add(view);
jframe.setUndecorated(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setState(Frame.ICONIFIED);
jframe.setState(Frame.NORMAL);
//jframe.setVisible(true);

If I uncomment jframe.setVisible(true) than everything works. But user will see this frame that I want to avoid.

So the question is: How to paint hidden control?

Inside Swing Component.java class all paint methods first check if the component is visible:



    public void paint(Graphics g) {
        if (isShowing()) {
            // rest of the code...
        }
    }


I've tried to create inherit class ShowingFrame extends JFrame, that override isShowing and always return true. But this not helps to.

Upvotes: 1

Views: 1550

Answers (3)

camickr
camickr

Reputation: 324147

If I uncomment jframe.setVisible(true) than everything works. But user will see this frame that I want to avoid.

You can set the frame location so that it is not visible on the screen. Maybe something like:

frame.pack();
Dimension d = frame.getSize();
frame.setLocation(-d.witdh, 0);

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328754

Swing (and the Java Graphics API) is optimized to stop rendering as soon as possible.

So the solution is to create a BufferedImage, get the Graphics instance from it and then call component.paint(g); with it.

Now you have a tab component. Try to get the content of the tab instead of rendering the tab itself. If that doesn't work, you can try to clone the tree of children, create a new JPanel, attach the children and render the result. But cloning can become tedious if the models don't behave well.

See this question for some code: Swing: Obtain Image of JFrame

Upvotes: 2

dkatzel
dkatzel

Reputation: 31648

Why do you want to paint something that is not visible? Your computer does not want to waste CPU cycles rendering graphics that can't be seen. In fact, there is a lot of computations done to see what parts of each window are visible and only paint the visible parts (the so called clip window).

If you want to paint something so you can use it later or save it you can always create a BufferedImage of the size you want and paint to that.

Upvotes: 1

Related Questions