打开组合框的面板的屏幕截图

rdo*_*nuk 5 java swing screenshot popup jcombobox

我有一个JPanel包含一个JComboBox.我打算在JComboBox打开时截取此面板的截图.但我不能这样做.任何的想法?

如果您运行此代码然后Alt-P在组合打开时按,您将看到问题.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ser 5

下拉弹出窗口不是JComboBox的组件层次结构的一部分,因此不是作为其一部分绘制的,而是独立绘制的.

解决方案是使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)