在 JFrame 中繪製函數 f(x) = sin(2x) + cos(3x) 的波形圖。建立座標軸,計算像素增量將數學座標映射至螢幕座標,逐段繪製線段形成曲線。
import java.awt.*;
import javax.swing.*;
public class FunctionPlot extends JFrame {
public static void main(String[] args) { new FunctionPlot().repaint(); }
FunctionPlot() {
super("Function Plot");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(310, 310);
setVisible(true);
}
double f(double x) { return Math.sin(2*x) + Math.cos(3*x); }
public void paint(Graphics g) {
int w = getSize().width, h = getSize().height;
int cx = w/2, cy = h/2;
double max = 5.0;
double xStep = 2*max / w;
double yScale = cy / max;
g.drawString("sin(2x)+cos(3x)", 10, 40);
g.setColor(Color.RED);
g.drawString("0", cx+5, cy+12);
g.drawString(String.valueOf(max), cx-20, 40);
g.drawString(String.valueOf(max), w-20, cy+12);
// 座標軸
g.drawLine(0, cy, w, cy); // X軸
g.drawLine(cx, 0, cx, h); // Y軸
g.setColor(Color.BLUE);
for (int px = 0; px < w-1; px++) {
double x0 = -max + px * xStep;
double x1 = x0 + xStep;
int y0 = cy - (int)(f(x0) * yScale);
int y1 = cy - (int)(f(x1) * yScale);
g.drawLine(px, y0, px+1, y1);
}
}
}
教學重點:
w。