package jp.gr.javacons.industry.seminar.barmeter; import java.awt.*; import java.awt.event.*; import java.io.Serializable; public class BarMeter extends Component implements Serializable { // Double Buffering 用イメージ transient protected Image image = null; transient protected Graphics graphics = null; // 画面の大きさに関連したプロパティ protected int width = 0; protected int height = 0; // リサイズのチェック用フラグ protected boolean resizeFlag = false; // メータの最小/最大値 protected double minimum = 0; protected double maximum = 100; // メータが指す値 protected double value = 0; public BarMeter(){ super(); enableEvents(AWTEvent.COMPONENT_EVENT_MASK); } public void processComponentEvent(ComponentEvent e){ if(e.getID() == ComponentEvent.COMPONENT_RESIZED){ resizeFlag = true; repaint(); } super.processComponentEvent(e); } public Dimension getPreferredSize(){ return getMinimumSize(); } public Dimension getMinimumSize(){ return new Dimension(50, 100); } public void setMinimum(double minimum){ this.minimum = minimum; } public double getMinimum(){ return this.minimum; } public void setMaximum(double maximum){ this.maximum = maximum; } public double getMaximum(){ return this.maximum; } public void setValue(double value){ this.value = value; repaint(); } // バーの描画 protected void drawBar(Graphics g, double value){ // 指示値の相対値を算出 double val = (value - minimum)/ (maximum - minimum); // グラフ上の高さに変換 val *= height; int y = height - (int)val; int h = (int)val; // バーの色を設定 // Component の前景色を利用する g.setColor(this.getForeground()); // バーを描画 g.fillRect(0, y, width, h); } public void update(Graphics g){ // 画面のクリアは行わない paint(g); } public void createBufferImage(){ // アプレットのサイズをえる Dimension size = this.getSize(); width = size.width; height = size.height; if(width != 0 && height != 0){ // イメージの生成 image = this.createImage(width, height); graphics = image.getGraphics(); } } public void paint(Graphics g){ // ダブルバッファリング用のイメージがなければ、 // 生成し、グラフィックコンテキストをえる。 // また、リサイズされたときもバッファイメージを生成する if(image == null || resizeFlag){ createBufferImage(); resizeFlag = false; } // 背景色で塗りつぶす graphics.setColor(this.getBackground()); graphics.fillRect(0, 0, width, height); // バーの描画 drawBar(graphics, value); // イメージバッファの描画 if(image != null){ g.drawImage(image, 0, 0, width, height, this); } } }