コンポーネントの画像キャプチャをしてファイルに保存する
戻る
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
* $Id: SavingImageOfComponent.html,v 1.1 2009/06/22 16:11:56 kishi Exp kishi $
*/
public class SavingImageOfComponent {
public static void main( String[] args ) {
JFrame f = new JFrame( "SavingImageOfComponent" );
Container container = f.getContentPane();
JTextArea ta1 = new JTextArea();
ta1.setBackground( Color.cyan );
JTextArea ta2 = new JTextArea();
ta2.setBackground( Color.white );
ta2.setText( "コンポーネントの画像キャプチャをしてファイルに保存します" );
final Component comp = container.add( new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
new JScrollPane( ta1 ),
new JScrollPane( ta2 ) ) );
JPanel southPanel = new JPanel();
southPanel.setBackground( Color.black );
container.add( southPanel, BorderLayout.SOUTH );
JButton save = ( JButton ) southPanel.add( new JButton( "コンポーネントの画像を保存" ) );
save.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent evt ) {
try {
int w = comp.getWidth(), h = comp.getHeight();
BufferedImage image = new BufferedImage( w, h,
BufferedImage.TYPE_INT_RGB );
Graphics2D g2 = image.createGraphics();
comp.paint( g2 );
g2.dispose();
ImageIO.write( image, "jpeg", new File( "savedImage.jpeg" ) );
} catch ( IOException e ) {
System.err.println( e );
}
}
}
);
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
f.setSize( 400, 400 );
f.setVisible( true );
}
}
戻る