我有一个CompSci的学校作业,我们需要为线性方程式创建一个图。该图应具有绘制的轴,并且应具有从两个方程式绘制的两条线。我使图形本身正常工作,但似乎无法弄清楚如何正确设置直线的坐标。目前,我正在使用以下代码创建坐标并将其发送到图形:
m.print("Slope as decimal: ");
//gets slope of line. This will be changed so it will accept fractions like Rise/Run but not until the rest of the functionality works.
double lslope = m.readDouble();
//gets y intercept as B
m.print("B as decimal: ");
double lb = m.readDouble();
//corresponds to the first coordinate
double x11=0;
double y11 = lslope*x11-lb*50;
//corresponds to the second coordinate
double x21=1000;
double y21 = lslope*x21-lb*50;
//outputs the coordinates of the two points just for the user's conveinience
m.println(""+x11+"\n"+y11+"\n"+x21+"\n"+y21);
//wingraph is a JFrame
wingraph graph = new wingraph("Graph");
graph.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
graph.setSize(1000,1000);
graph.setResizable(false);
//the second set of 4 numbers will be a second line, but to get the graph working I'm just focusing on using one set. The setCoords method just sets the value of 8 coordinates inside a JFrame class which paints the X and Y axis in black, and then paints two lines with the specified coordinates in red.
graph.setCoords(x11, y11, x21, y21, 1000,1000,1000,1000);
//displays the graph
graph.setVisible(true);
通过反转用户输入的斜率,我可以使线正常工作,但前提是lslope
等于1。如何正确操作整数,以便无论斜率如何都能很好地显示图形有小数点,是整数还是正数或负数?
如果有帮助,我正在使用的JFrame的代码是:
public class wingraph extends JFrame{
public wingraph(String title){
super(title);
setLayout(new FlowLayout());
}
double xCoord1 = 0, yCoord1 = 0, xCoord2 = 0, yCoord2 = 0, xCoord12 = 0, yCoord12 = 0, xCoord22 = 0, yCoord22 = 0;
public void setCoords(double x1, double y1, double x2, double y2, double x12, double y12, double x22, double y22){
xCoord1 = x1;
yCoord1 = y1;
xCoord2 = x2;
yCoord2 = y2;
xCoord12 = x12;
yCoord12 = y12;
xCoord22 = x22;
yCoord22 = y22;
}
public void paint(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.BLACK);
g.drawLine(this.getWidth()/2, 0, this.getWidth()/2, this.getHeight());
g.drawLine(0, this.getHeight()/2, this.getWidth(), this.getHeight()/2);
g.drawString("0",this.getWidth()/2-10,this.getHeight()/2-5);
g.setColor(Color.red);
g.drawLine((int) xCoord1,(int) yCoord1,(int) xCoord2,(int) yCoord2);
g.drawLine((int) xCoord12,(int) yCoord12,(int) xCoord22,(int) yCoord22);
}
}
感谢您的帮助。
修改
我的代码运行示例如下:
所有这些都存在问题,因为我需要将它们全部集中在轴和正确的格式上,例如:
对于仍然不清楚的情况,我深表歉意,但是我对Java还是陌生的,除了在笛卡尔平面上用等式y = mx + b
绘制2条线外,我对如何确切地解释我想要的内容并不熟悉。
编辑2
如果用户为lslope
输入1,为b
输入0,我希望x和y变量为:
x11 = 0;
y11 = 1000;
x21 = 1000;
y21 = 0;
如果lslope = 2
和b = 5
我希望x和y变量为:
x11 = 0
y11 = 745;
x21 = 1000;
y21 = 245;
如果lslope = -1
和b = 10
我希望x和y变量为:
x11 = 0
y11 = 240;
x21 = 1000;
y21 = 740;