2012-08-25 53 views
3

我想繪製一個圖像(與鼠標)在一個JPanel,這是工作,但是當我嘗試採取面板的屏幕截圖並生成此圖像時,我只可以看到沒有用鼠標繪製的圖像背景。面板背景圖像採取屏幕截圖

這是我的代碼來生成背景 Panel.java

@Override 
protected void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    g.drawImage(this.createImage("/imagenes/cuerpoHumano.png").getImage(), 0, 0, null); 
} 

這是我的代碼來繪製鉛筆在圖像: Panel.java

private void formMouseDragged(java.awt.event.MouseEvent evt) { 
    x = evt.getX(); 
    y = evt.getY(); 

    this.getGraphics().setColor(Color.RED); 
    this.getGraphics().fillOval(x, y, 4, 4); 
}         

這是生成屏幕截圖的代碼

Dimension size = panel.getSize(); 
BufferedImage image = (BufferedImage) panel.createImage(size.width, size.height); 
Graphics g = image.getGraphics(); 
panel.paint(g); 
g.dispose(); 
try { 
    String fileName = UUID.randomUUID().toString().substring(0, 18); 
    ImageIO.write(image, "jpg", new File(path, fileName + ".jpg")); 

} catch (IOException e) { 
    e.printStackTrace(); 
} 
+2

不要在「paint(...)」或「paintComponent(...)」方法內讀取圖像或任何文件,因爲這會不必要地降低圖形速度。這些方法需要儘可能快,以使您的圖形顯示響應。爲什麼不一次只讀一次圖像,將它存儲到一個變量中,然後在'paintComponent(...)'中使用它? –

+1

嘗試讀取'paintComponent'中的圖像的問題是固定的 - 'g.drawImage(this.createImage(「/ imagenes/cuerpoHumano.png」)。getImage(),0,0,null);'應該是'g.drawImage(this.createImage(「/ imagenes/cuerpoHumano.png」)。getImage(),0,0,this);' –

回答

3

當您拍攝屏幕截圖時,會調用paintComponent()方法。這意味着它只會畫你的形象。您必須將鼠標移動到某個模型中,然後在paintComponent()方法中繪製模型的內容。在鼠標移動過程中,通過在面板上調用repaint()來觸發此方法。

+1

同意。 1+。還要提到你幾乎從不會通過調用組件上的'getGraphics()'來獲得Graphics對象。在BufferedImage上,是的,但不在組件上。獲得的圖形將不會持續。 –

0

我認爲這是可行的代碼。

public class PanelImagenCuerpoHumano extends JPanel { 

    private int x = -1; 
    private int y = -1; 
    private Image image = null; 
    private ArrayList<Point> puntos = new ArrayList<Point>(); 

    public PanelImagenCuerpoHumano() { 

     image = new ImageIcon(getClass() 
      .getResource("/imagenes/cuerpoHumano.png")).getImage(); 

     this.addMouseMotionListener(new MouseMotionListener() { 

      @Override 
      public void mouseDragged(MouseEvent e) { 
       x = e.getX(); 
       y = e.getY(); 
       puntos.add(new Point(x, y)); 
       repaint(); 
      } 

      @Override 
      public void mouseMoved(MouseEvent e) { 
      } 
     }); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 

     g.drawImage(image, 0, 0, null); 
     for (Point p : puntos) { 
      g.setColor(Color.red); 
      g.fillOval(p.x, p.y, 3, 3); 
     } 
    } 
} 
+0

也考慮'MouseMotionAdapter'。 – trashgod

+0

看起來不錯,很高興它的作品! –