[メニュー] [ホーム]

テキストフィールド配列と棒グラフ


---(アプリケーションの説明)---

テキストフィールドの数字で棒グラフを描きます。

---(ソースリスト)---

//Sample25
import java.applet.Applet;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Sample25 extends Applet implements ActionListener {
  private static final int rect_pitch = 40;
  private static final int rect_width = 10;
  private static final int origin_X = 100;
  private static final int origin_Y = 300;
  private static final String init_value = "100";
  private static final int element_count = 12;
  private static final String window_title = "テキストフィールド配列と棒グラフ";
  private static final int window_width = 640;
  private static final int window_height = 400;
  private static final long serialVersionUID = 5020119670022730653L;
  Button b01;
  TextField[] tf = new TextField[12];
  // 初期処理
  @Override
  public void init() {
    this.setSize(Sample25.window_width, Sample25.window_height);
    this.add(new Label(Sample25.window_title));
    this.setLayout(new FlowLayout());
    this.b01 = new Button("Graph");
    this.b01.addActionListener(this);
    for (int i = 0; i < Sample25.element_count; i++) {
      final int tf_size = 3;
      this.tf[i] = new TextField(Sample25.init_value, tf_size);
      this.add(this.tf[i]);
    }
    this.add(this.b01);
  }
  // 描画
  @Override
  public void paint(final Graphics g) {
    g
        .clearRect(0, 0, Sample25.window_width - 1,
            Sample25.window_height - 1);
    for (int i = 0; i < Sample25.element_count; i++) {
      final String rs = this.tf[i].getText();
      if (rs != null) {
        try {
          final int rect_height = Integer.parseInt(rs);
          g.drawRect(Sample25.origin_X + i * Sample25.rect_pitch,
              Sample25.origin_Y - rect_height,
              Sample25.rect_width, rect_height);
        } catch (final NumberFormatException e) {
        }
      }
    }
  }
  // イベント
  public void actionPerformed(final ActionEvent ae) {
    if (ae.getSource() == this.b01) {
      this.repaint();
    }
  }
}
.