如何将组件(如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)
...
答案 0 :(得分:2)
此example说明使用panel.paint(g2d)
呈现JPanel
中JLabel
个BufferedImage
个实例。然后缩放图像并显示在面板下方以供参考。
答案 1 :(得分:1)
你可以假设我正在绘制一个BufferedImage,事实上我有时会这样做。
请参阅Screen Image,它也可以创建组件图像。