1 | package com.ether; |
---|
2 | |
---|
3 | import gov.noaa.pmel.sgt.JPane; |
---|
4 | import gov.noaa.pmel.sgt.swing.JPlotLayout; |
---|
5 | import org.jetbrains.annotations.NotNull; |
---|
6 | |
---|
7 | import javax.swing.*; |
---|
8 | import java.awt.*; |
---|
9 | import java.awt.image.BufferedImage; |
---|
10 | |
---|
11 | /** |
---|
12 | * @Author : E.Mo.. |
---|
13 | * This class convert a JPanel into a BufferedImage |
---|
14 | */ |
---|
15 | public class JPanelToImageManager |
---|
16 | { |
---|
17 | public JPanelToImageManager( @NotNull final JPane jPanel ) |
---|
18 | { |
---|
19 | _target = jPanel; |
---|
20 | } |
---|
21 | |
---|
22 | /** |
---|
23 | * @return the image corresponding to the JPanel |
---|
24 | */ |
---|
25 | public BufferedImage saveAsImage() |
---|
26 | { |
---|
27 | return paintComponent( _target ); |
---|
28 | } |
---|
29 | |
---|
30 | /** |
---|
31 | * @param component the component to convert |
---|
32 | * @return the buffer of the converted image |
---|
33 | */ |
---|
34 | private BufferedImage paintComponent( @NotNull final Component component ) |
---|
35 | { |
---|
36 | if( 0 >= component.getWidth() || 0 >= component.getHeight() ) |
---|
37 | return null; |
---|
38 | |
---|
39 | // Set it to it's preferred size. (optional) |
---|
40 | component.setSize( component.getPreferredSize() ); |
---|
41 | layoutComponent( component ); |
---|
42 | |
---|
43 | final BufferedImage bufferedImage = new BufferedImage( component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_RGB ); |
---|
44 | |
---|
45 | if( component instanceof JPlotLayout ) |
---|
46 | { |
---|
47 | final Graphics2D graphics2D = bufferedImage.createGraphics(); |
---|
48 | graphics2D.setBackground( Color.red ); |
---|
49 | ( (JPlotLayout) component ).draw( graphics2D ); |
---|
50 | } |
---|
51 | else |
---|
52 | { |
---|
53 | final CellRendererPane crp = new CellRendererPane(); |
---|
54 | crp.add( component ); |
---|
55 | crp.paintComponent( bufferedImage.createGraphics(), component, crp, component.getBounds() ); |
---|
56 | } |
---|
57 | return bufferedImage; |
---|
58 | } |
---|
59 | |
---|
60 | private void layoutComponent( final Component component ) |
---|
61 | { |
---|
62 | synchronized( component.getTreeLock() ) |
---|
63 | { |
---|
64 | component.doLayout(); |
---|
65 | if( component instanceof Container ) |
---|
66 | { |
---|
67 | for( final Component child : ( (Container) component ).getComponents() ) |
---|
68 | layoutComponent( child ); |
---|
69 | } |
---|
70 | } |
---|
71 | } |
---|
72 | |
---|
73 | // Panel to convert into an image |
---|
74 | @NotNull |
---|
75 | private final JPane _target; |
---|
76 | } |
---|