图形功能

时间:2017-05-15 00:17:36

标签: java graph graphing

我一般都是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);
    }
}

给了我

enter image description here

我现在要做的是绘制余弦函数,我不知道如何绘制,因为它是cos(2x)而不是2cos(x)。

我还想更改缩放比例以使细分看起来不那么小(可能是图形标记?但不是特别重要)。

我想添加一些内容,以便一次只显示一个功能。

2 个答案:

答案 0 :(得分:1)

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

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

它有点比其他人更棘手,因为Math.cos返回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...

答案 1 :(得分:0)

+以接受的答案为基础,生成所需的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]

cos(2x) 0-2pi

相关问题