J2SE 利用Java函式畫曲線
阿新 • • 發佈:2019-01-25
[java]
view plain
copy
print?
- publicclass Function extends JFrame {
- privatestaticfinaldouble WIDTH = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
- privatestaticfinaldouble HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
- privatestaticfinalint INCREMENT =
- publicstaticvoid main(String[] args) {
- new Function();
- }
- public Function() {
- this.setTitle("畫影象sinx/x");
- this.setLocation(50, 50);
- this.setVisible(true);
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.getContentPane().setBackground(Color.BLUE);
- this.setExtendedState(JFrame.MAXIMIZED_BOTH);
- }
- @Override
- publicvoid paint(Graphics g) {
- super.paint(g);
- Graphics2D g2d = (Graphics2D) g;
- Color source = g2d.getColor();
- g2d.setColor(Color.WHITE);
- g2d.drawString("sinx/x 的影象", 50, 50);
- // 畫 X 軸
- g2d.drawLine(INCREMENT, (int)HEIGHT/2, (int)WIDTH-INCREMENT, (int)HEIGHT/2);
- g2d.drawLine((int)WIDTH-INCREMENT, (int)HEIGHT/2, (int)WIDTH-10, (int)HEIGHT/2-5);
- g2d.drawLine((int)WIDTH-INCREMENT, (int)HEIGHT/2, (int)WIDTH-10, (int)HEIGHT/2+5);
- // 畫 Y 軸
- g2d.drawLine((int)WIDTH/2, 40, (int)WIDTH/2, (int)HEIGHT-50);
- g2d.drawLine((int)WIDTH/2, 40, (int)WIDTH/2-10, 50);
- g2d.drawLine((int)WIDTH/2, 40, (int)WIDTH/2+10, 50);
- // 將當前畫筆移動到中心
- g2d.translate((int) WIDTH / 2, (int) HEIGHT / 2);
- // 利用GeneralPath類來畫曲線
- GeneralPath gp = new GeneralPath();
- // 將GeneralPath的例項gp的畫筆移動到當前畫面的中心,但是這個點是相對於g2d畫筆的中心的
- gp.moveTo(0, 0);
- // 畫sin(x)/x 的影象
- // drawSinxDX(gp, g2d);
- // sin(x)的影象
- drawSinx(gp, g2d);
- // cos(x)的影象
- // drawCosx(gp, g2d);
- // tan(x)的影象
- // drawTanx(gp, g2d);
- g2d.setColor(source);
- }
- privatevoid drawTanx(GeneralPath gp, Graphics2D g2d) {
- for (double i = 0.000001; i <= 8*Math.PI; i+=0.0001*Math.PI) {
- gp.lineTo(20*i, 100*-Math.tan(i));
- }
- g2d.draw(gp);
- // 將當前畫筆以原點為中心,旋轉180度,畫奇函式(關於原點對稱)
- g2d.rotate(Math.PI);
- g2d.draw(gp);
- }
- privatevoid drawCosx(GeneralPath gp, Graphics2D g2d) {
- for (double i = 0.000001; i <= 8*Math.PI; i+=0.0001*Math.PI) {
- gp.lineTo(20*i, 100*-Math.cos(i));
- }
- g2d.draw(gp);
- // 將當前畫筆以Y中為對稱軸,畫偶函式(關於Y軸對稱)
- g2d.scale(-1, 1);
- g2d.draw(gp);
- }
- privatevoid drawSinx(GeneralPath gp, Graphics2D g2d) {
- for (double i = 0.000001; i <= 8*Math.PI; i+=0.0001*Math.PI) {
- gp.lineTo(20*i, 100*-Math.sin(i));
- }
- g2d.draw(gp);
- g2d.rotate(Math.PI);
- g2d.draw(gp);
- }
- privatevoid drawSinxDX(GeneralPath gp, Graphics2D g) {
- for (double i = 0.000001; i <= 8*Math.PI; i+=0.0001*Math.PI) {
- gp.lineTo(20*i, 100*-Math.sin(i)/i);
- }
- g.draw(gp);
- g.scale(-1, 1);
- g.draw(gp);
- }