(ファイル名: Drawer2.java)
// 描画用クラス // Copyright (C) 2000 by Hidehiko Masuhara // 使い方は Drawer2Sample.java を参照。 // Java のグラフィクスライブラリを使うための宣言 import java.awt.*; import java.awt.event.*; public class Drawer2 extends Canvas implements Runnable, MouseListener, WindowListener { Image offScreenImage; static final int topMargin = 0; // for flicker-free drawing public void update(Graphics g) { paint(g); } // merely put the off-screen image on the screen public void paint(Graphics g) { if (offScreenImage != null) g.drawImage(offScreenImage,0,topMargin,this); } // create a Frame with the specified size, // it also sets up the off-screen image, and an updater thread // for asynchronous drawing. static Graphics createFrame(int width, int height) { return new Drawer2(width,height+topMargin).getGraphicsObject(); } // 押されたらプログラムを終了させる public void windowClosing(WindowEvent we) {System.exit(0);} public void windowActivated(WindowEvent e){} public void windowClosed(WindowEvent e){} public void windowDeactivated(WindowEvent e){} public void windowDeiconified(WindowEvent e){} public void windowIconified(WindowEvent e){} public void windowOpened(WindowEvent e){} // クリックされたらプログラムを終了させる public void mouseClicked(MouseEvent me) {System.exit(0);} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mousePressed(MouseEvent e){} public void mouseReleased(MouseEvent e) {} public Drawer2(int width, int height) { super(); Frame f = new Frame("A Graphics Window - Computer Programming I"); // Closeボタンが押されたときの処理を設定しておく。 f.addWindowListener(this); // 画面をクリックされたときの処理も設定。 this.addMouseListener(this); int margin = 30; f.setSize(width,height); // set the size of the window f.add(this); f.show(); // put this frame on a screen java.awt.Dimension d = this.getSize(); f.setSize(width-d.width+width, height-d.height+height); f.doLayout(); // create an off-screen image of the window for asynchronous drawing this.offScreenImage = this.createImage(width,height); Thread updater = new Thread(this); updater.setDaemon(true); updater.start(); } Graphics getGraphicsObject() {return offScreenImage.getGraphics();} // for background repainting final static int interval = 100; // msec. // a background thread will execute the following method public void run() { try { while (true) { if (this.isShowing()) this.repaint(); Thread.currentThread().sleep(interval); } } catch (InterruptedException e) { ; // do nothing } } }
Hidehiko Masuhara, December 2000