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

时间:2014-06-26 07:20:08

标签: java swing popup screenshot 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);
    }
}

2 个答案:

答案 0 :(得分: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();
    }
}

答案 1 :(得分:2)

  • 默认情况下,AWT / Swing中的所有Popup都为Heavyweight(对已经可见的弹出窗口的任何更改必须为pack()&#39;)

  • 此处不需要使用awt.Robot进行截屏,必须在层次结构中获得重量级BasicsComboBoxPopup的顶级重量级组件,这是来自{{1}的RootPane }}

e.g。

enter image description here

enter image description here

来自代码

JFrame