// DrawGraph.java // import java.applet.*; import java.awt.*; import java.awt.event.*; public class DrawGraph extends Applet implements ActionListener { private static final String message = "graph of a function with 1 variable"; private int N = 100; private double a = 0.0; private double b = 2 * Math.PI; private double wmargin = (b - a) / 10; // 座標系の変換のためのパラメーター private double ratiox, ratioy, X0, Y0; // ユーザーとのインターフェイス (パラメーターの入力) private Label labelN; private TextField inputN; private Button startB; // 準備 (変数の用意と座標系の初期化など) public void init() { // setLayout(null); labelN = new Label("N"); add(labelN); labelN.setBounds(100, 60, 200, 30); inputN = new TextField("" + N); add(inputN); inputN.setBounds(300, 60, 100, 30); startB = new Button("Restart"); add(startB); startB.setBounds(400, 60, 100, 30); startB.addActionListener(this); } // ボタンを押されたら、テキスト・フィールドの内容を読み取って、再描画 public void actionPerformed(ActionEvent e) { if (e.getSource() == startB) { String str = inputN.getText(); N = Integer.parseInt(str); repaint(); } } // グラフを描きたい関数 private double f(double x) { return Math.sin(3 * x) + Math.sin(5 * x); } // 座標変換の準備 private void space(double x0, double y0, double x1, double y1) { X0 = x0; Y0 = y0; ratiox = 500 / (x1 - x0); ratioy = 500 / (y1 - y0); } // ユーザー座標 (ワールド座標系) をウィンドウ座標 (デバイス座標系) private int wx(double x) { return (int)(ratiox * (x - X0)); } // ユーザー座標 (ワールド座標系) をウィンドウ座標 (デバイス座標系) private int wy(double y) { return 500 - (int)(ratioy * (y - Y0)); } // x[], u[] の内容を折れ線グラフとして描く private void drawGaph(Graphics g, double x[], double u[]) { for (int i= 0; i < N; i++) g.drawLine(wx(x[i]), wy(u[i]), wx(x[i + 1]), wy(u[i + 1])); } public void paint(Graphics g) { double h = (b - a) / N; double [] u, x; // ベクトルを確保する x = new double[N+1]; u = new double[N+1]; for (int i = 0; i <= N; i++) x[i] = a + i * h; // タイトルを表示する g.setColor(Color.black); g.setFont(new Font("Helvetica", Font.BOLD, 24)); g.drawString(message, 40, 30); // 関数値を計算する for (int i = 0; i <= N; i++) u[i] = f(x[i]); // 関数の値の範囲を調べる double min, max; min = u[0]; max = u[0]; for (int i = 1; i <= N; i++) { if (u[i] > max) max = u[i]; else if (u[i] < min) min = u[i]; } // 関数の値の範囲を元にして座標変換を決める double hmargin = (max - min) / 10; if (hmargin == 0) hmargin = 1; space(a - wmargin, min - hmargin, b + wmargin, max + hmargin); // 関数のグラフを描く drawGaph(g, x, u); } }