Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Screenshot of a panel with opened comboboxes

I have a JPanel which includes a JComboBox. I am trying to take a screenshot of this panel when JComboBox is open. But I couldn't do it. Any idea?

If you run this code then press Alt-P when combo is open, you will see the problem.

public class ScreenShotDemo {
    /**
     * @param args
     */
    public static void main(String[] args) {
        final JPanel JMainPanel = new JPanel(new BorderLayout());

        JPanel jp = new JPanel();
        jp.add(new JComboBox<String>(new String[] { "Item1", "Item2", "Item3" }));

        final JPanel jImage = new JPanel();

        JMainPanel.add(jp, BorderLayout.WEST);
        JMainPanel.add(jImage, BorderLayout.CENTER);

        jp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.ALT_DOWN_MASK), "screenshot");
        jp.getActionMap().put("screenshot", new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                BufferedImage bf = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
                JMainPanel.paint(bf.getGraphics());
                jImage.getGraphics().drawImage(bf, 0,0,jImage);
            }
        });

        final JFrame jf = new JFrame();
        jf.getContentPane().add(JMainPanel);
        jf.setSize(500, 500);
        jf.setVisible(true);
    }
}
like image 559
rdonuk Avatar asked Jun 26 '14 07:06

rdonuk


1 Answers

The dropdown popup window is not part of the JComboBox's component hierarchy, and therefore is not drawn as part of it, but independently.

A solution to this is to take an actual screen shot using java.awt.Robot:

@Override
public void actionPerformed (ActionEvent arg0) {

    Point p = new Point(0, 0);
    SwingUtilities.convertPointToScreen(p, JMainPanel);
    Rectangle screenBounds = new Rectangle(p.x, p.y, JMainPanel.getSize().width, JMainPanel.getSize().height);

    try {
        Robot robot = new Robot();
        BufferedImage screenCapture = robot.createScreenCapture(screenBounds);

        jImage.getGraphics().drawImage(screenCapture, 0, 0, jImage);
    } catch (AWTException e) {
        e.printStackTrace();
    }
}
like image 146
Peter Walser Avatar answered Dec 04 '22 20:12

Peter Walser