source: ether_megapoli/trunk/service/implementation/com/ether/JPanelToImageManager.java @ 130

Last change on this file since 130 was 130, checked in by vmipsl, 13 years ago

[Visualization] interface quite finish

File size: 2.1 KB
Line 
1package com.ether;
2
3import gov.noaa.pmel.sgt.JPane;
4import gov.noaa.pmel.sgt.swing.JPlotLayout;
5import org.jetbrains.annotations.NotNull;
6
7import javax.swing.*;
8import java.awt.*;
9import java.awt.image.BufferedImage;
10
11/**
12 * @Author : E.Mo..
13 * This class convert a JPanel into a BufferedImage
14 */
15public 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}
Note: See TracBrowser for help on using the repository browser.