将swing组件绘制到Graphics

时间:2013-02-22 19:31:03

标签: java swing graphics jpanel paint

如何将组件(如JPanel)绘制到我选择的图形中, 仿佛它是屏幕?

谷歌没有运气。

我尝试过:

JPanel p = new JPanel();
p.setSize(32, 32);
p.setLocation(8, 8);

p.add(new JLabel(...));
p.add(new JLabel(...));
p.add(new ImageIcon(...));

Graphics g = getSomeGraphics();
p.paint(g);

但是,最后一条指令会导致

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.RepaintManager.getVolatileOffscreenBuffer(Unknown Source)
    at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
    at javax.swing.BufferStrategyPaintManager.paint(Unknown Source)
    at javax.swing.RepaintManager.paint(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    ...

2 个答案:

答案 0 :(得分:2)

example说明使用panel.paint(g2d)呈现JPanelJLabelBufferedImage个实例。然后缩放图像并显示在面板下方以供参考。

image

答案 1 :(得分:1)

  

你可以假设我正在绘制一个BufferedImage,事实上我有时会这样做。

请参阅Screen Image,它也可以创建组件图像。