java黑皮书第十五章第十二题,画出正弦函数的图形

该程序使用JavaSwing库创建一个GUI窗口,显示正弦函数的图形。它通过计算一系列点的坐标,然后在窗口中绘制这些点来形成正弦曲线。坐标轴、标签以及适当的缩放比例都被考虑在内。
摘要由CSDN通过智能技术生成

编程练习题15.12(画出正弦函数的图形)编写一个程序,画出正弦函数的图形。

代码展示

import java.awt.*;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SinFrame extends JFrame {
	public SinFrame() {
		Container container = this.getContentPane();
		container.setLayout(new BorderLayout());
		SinPanel sinPanel = new SinPanel();
		container.add(sinPanel, BorderLayout.CENTER);
		this.setTitle("Show Sin Fuction!");
		this.setSize(new Dimension(400, 400));
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = this.getSize();
		this.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
		this.setVisible(true);
	}

	public static void main(String[] args) {
		new SinFrame();
	}
}

class SinPanel extends JPanel {
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		Dimension panelSize = this.getSize();
		Location center = new Location(panelSize.width / 2, panelSize.height / 2);
		int radius = (int) ((Math.min(panelSize.width, panelSize.height) / 2) * 0.9);
// 确定每个点的坐标
		int[] x = new int[2 * radius + 1];
		int[] y = new int[2 * radius + 1];
		for (int i = 0; i < 2 * radius + 1; i++) {
			x[i] = center.x - radius + i;
			double y1 = Math.sin(((double) (-radius + i) / radius) * 4 * Math.PI);// 这个很重要,sin()里面必须为double值
			int y2 = (int) (y1 * 100);
			y[i] = center.y - y2;
		}
		g.setColor(Color.black);
// 画坐标轴
		g.drawLine(center.x - radius, center.y, center.x + radius, center.y);
		g.drawLine(center.x, center.y - radius, center.x, center.y + radius);
		g.drawLine(center.x + radius, center.y, center.x + radius - 10, center.y - 7);
		g.drawLine(center.x + radius, center.y, center.x + radius - 10, center.y + 7);
		g.drawLine(center.x, center.y - radius, center.x - 7, center.y - radius + 10);
		g.drawLine(center.x, center.y - radius, center.x + 7, center.y - radius + 10);
		g.drawPolyline(x, y, 2 * radius + 1);
		g.setColor(Color.red);
		g.setFont(new Font("ScanSerif", Font.BOLD, 12));
		g.drawString("X", center.x + radius, center.y - 10);
		g.drawString("Y", center.x + 10, center.y - radius);
	}
}

class Location {
	public int x;
	public int y;

	public Location(int x, int y) {
		this.x = x;
		this.y = y;
	}
}

 结果演示

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值