2010-11-22 8 views
6

コンポーネントの内容とそのすべてのサブコンポーネントをビットマップに描画する必要があります。コンポーネントをビットマップにペイントする

public void printComponent(Component c, String format, String filename) throws IOException { 
// Create a renderable image with the same width and height as the component 
BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB); 

    // Render the component and all its sub components 
    c.paintAll(image.getGraphics()); 

    // Render the component and ignoring its sub components 
    c.paint(image.getGraphics()); 
// Save the image out to file 
ImageIO.write(image, format, new File(filename)); 

}

しかし、私は、このコンポーネントの唯一地域を描画するための方法を見つけることができませんでした:私は、コンポーネント全体を描きたい場合は 次のコードは完璧に動作します。

答えて

6

あなたはこのように翻訳する必要があります:出力と

BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); 

Graphics g = image.getGraphics(); 
g.translate(-100, -100); 

c.paintComponent(g); 

g.dispose(); 

全例:

Resulting image

public static void main(String args[]) throws Exception { 

    JFrame frame = new JFrame("Test"); 
    frame.add(new JTable(new DefaultTableModel() { 
     @Override 
     public int getColumnCount() { 
      return 10; 
     } 
     @Override 
     public int getRowCount() { 
      return 10; 
     } 
     @Override 
     public Object getValueAt(int row, int column) { 
      return row + " " + column; 
     } 
    })); 

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(400, 300); 
    frame.setVisible(true); 

    BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); 
    Graphics g = image.getGraphics(); 
    g.translate(-100, -100); 

    frame.paintComponents(g); 

    g.dispose(); 

    ImageIO.write(image, "png", new File("frame.png")); 
} 
+0

ビットマップの点0,0で始まるコンポーネントの領域を描画しません! – Arutha

+0

私が設定したクリップは一例です。このリージョンをあなたに役立つものに設定する必要があります。 – dacwe

+0

ポイント(100,100)から100×100のシエズで始まる領域を描画するには、100 * 100のサイズのビットマップを作成する必要があるため、setClipメソッドのパラメータは何ですか? – Arutha

1

Screen Imageクラスがあなたのためにこのプロセスを簡素化します。

関連する問題