绘图功能

Graphing functions

总的来说,我是 Java 的新手,更不用说使用 GUI 了,我正在做一个任务来绘制 3 个函数:

x^3+x-3

x^3/100-x+10

cos2theta

(余弦的四叶丁香) 有域限制

0,4

-10,10

0 < x < 2pi

到目前为止,我已经绘制了前两个函数的粗略图表,不知道如何绘制第三个函数。

我有:

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


public class DrawingStuff extends JComponent {

public void paintComponent(Graphics g)
{   
     //w is x, and h is y (as in x/y values in a graph)
     int w = this.getWidth()/2;
     int h = this.getHeight()/2;

 Graphics2D g1 = (Graphics2D) g;
 g1.setStroke(new BasicStroke(2));
 g1.setColor(Color.black);
 g1.drawLine(0,h,w*2,h);
 g1.drawLine(w,0,w,h*2); 
 g1.drawString("0", w - 7, h + 13);


 Graphics2D g2 = (Graphics2D) g;
 g2.setStroke(new BasicStroke(2));
  g2.setColor(Color.red);
  //line1
  Polygon p = new Polygon();
  for (int x = 0; x <= 4; x++) {
      p.addPoint(w+x, h - ((x*x*x) + x - 3));

  }
  g2.drawPolyline(p.xpoints, p.ypoints, p.npoints);

  Polygon p1 = new Polygon();
  for (int x = -10; x <= 10; x++) {
      p1.addPoint(w + x, h - ((x*x*x)/100) - x + 10);
  }
  g2.drawPolyline(p1.xpoints, p1.ypoints, p1.npoints); 
}

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(800, 600);
    frame.setTitle("Graphs");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);  
    DrawingStuff draw = new DrawingStuff();
    frame.add(draw);
    frame.setVisible(true);
    }
}

这给了我

我现在想做的是绘制余弦函数图,我不确定如何绘制它,因为它是 cos(2x) 而不是 2cos(x)。

我还想更改缩放比例,使线段看起来不会那么小(也许还有图形标记?但不是特别重要)。

而且我想添加一些东西,以便一次只显示一个功能。

要添加最后一个函数,请执行与之前相同的操作(创建带点的多边形等),但使用新函数:

addPoint(w + x, h - Math.round(scale*Math.cos(2*x)))

它比其他的有点棘手,因为 Math.cos returns 一个 doubleaddPoint 需要一个 int。为了解决这个问题,我们四舍五入到最近的 int。然而,余弦的范围 [-1,1] 只包含三个我们可以四舍五入的整数。这会产生难看的余弦波(看起来像三角波)。

为了减轻这种丑陋,使用了比例因子。一个因子,比如 10,会使范围 [-10,10] 中有更多的整数,从而导致更平滑的波。

这个比例因子对您的其他功能也很有用,即根据需要使它们变大:

int scale = 10;
for (int x = 0; x <= 4; x++) {
    p.addPoint(w+scale*x, h - scale*((x*x*x) + x - 3));
}
//...lines skipped
for (int x = -10; x <= 10; x++) {
  p1.addPoint(w + scale*x, h - scale*((x*x*x)/100) - x + 10);
}

要一次只显示一个函数,只需在代码中添加 if 语句即可。

假设每个函数都有一个 JRadioButton

if(button1.isSelected()){
    Polygon p = new Polygon();
    for (int x = 0; x <= 4; x++) {
        p.addPoint(w+x, h - ((x*x*x) + x - 3));
    }
    g2.drawPolyline(p.xpoints, p.ypoints, p.npoints);
}
else if(button1.isSelected()){
    //other polygon
}
//etc...

+基于已接受的答案生成请求的 cos(2x) 图。

    final double MAX_X = 2 * Math.PI;
    final double SCALE = w / MAX_X;

    for (int x = 0; x <= w; ++x) {
        double xScaled = x / SCALE;
        p.addPoint(w + x, h - (int)Math.round(SCALE * Math.cos(2 * xScaled)));
    }

结果 cos(2x)[0, 2pi]