利用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的点的个数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值