利用Graphics类做的一些习题(四)

效果

在这里插入图片描述

题目

**15.11(绘图表示平方的函数)编写程序,绘制函数f(x)=x^2的图形

代码

package Test;

import javax.swing.*;
import java.awt.*;

public class Exercise15_11 extends JFrame {
    public Exercise15_11(){
       add(new drawFunc());
    }

    public static void main(String[] args) {
        Exercise15_11 frame=new Exercise15_11();
        frame.setTitle("Exercise16_9");
        frame.setSize(800,400);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

class drawFunc extends JPanel{
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        //x轴
        g.drawLine(50,200,400,200);
        //y轴
        g.drawLine(200,50,200,400);
        //x轴箭头
        g.drawLine(400,200,400-17,200-17);
        g.drawLine(400,200,400-17,200+17);
        //y轴箭头
        g.drawLine(200,50,200-17,50+17);
        g.drawLine(200,50,200+17,50+17);
        //x轴文字
        g.drawString("x",410,200);
        //y轴文字
        g.drawString("y",210,50);

        Polygon p=new Polygon();
        double scaleFactor=0.01;
        for (int x = -100 ; x <=100 ; x++) {
            p.addPoint(x+200,200-(int)(scaleFactor*x*x));
        }
        g.drawPolyline(p.xpoints,p.ypoints,p.npoints);
    }
}

思路解析

使用下面的 循环在多边形p中加入点

  	 Polygon p=new Polygon();
        double scaleFactor=0.01;
        for (int x = -100 ; x <=100 ; x++) {
            p.addPoint(x+200,200-(int)(scaleFactor*x*x));
        }
        g.drawPolyline(p.xpoints,p.ypoints,p.npoints);
    

对Graphics对象g使用 g.drawPolyline(p.xpoints,p.ypoints,p.npoints)来连接点,p.xpoints返回x坐标的数组,p.ypoints返回y坐标的数组,p.npoints返回Polygon对象p的点的个数。

发布了100 篇原创文章 · 获赞 25 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43576028/article/details/101898025