java 2D绘图

时间:2010-09-29 09:14:54

标签: java swing

我试图制作一个绘制函数图形的swing应用程序(现在很简单,例如x + 2) 但我有问题根据屏幕坐标制作我的点的数学坐标。 我希望它只是在我的图形中绘制一条从P1(0,1)到P2(1,2)的线。

这是我的代码:

import java.awt.*;
import javax.swing.*;  
public class Graph extends JPanel {

   protected void paintComponent(Graphics g) {
     int YP1,YP2;
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;

      int h = getHeight();
         int w = getWidth();
         // Draw axeX.
         g2.draw(new Line2D.Double(0, h/2, w, h/2)); //to make axisX in the middle
         // Draw axeY.
         g2.draw(new Line2D.Double(w/2,h,w/2,0));//to make axisY in the middle of the panel

                  //line between P1(0,1) and P2(1,2) to draw function x+1
    Point2D P1 = new Point2D.Double(w/2,(h/2)+1);
    Point2D P2 = new Point2D.Double((w/2)+1,(h/2)+2);
     g2.draw(new Line2D.Double(P1,P2));
}
public static void main(String[] args) {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.add(new Graphe());
      f.setSize(400,400);
      f.setLocation(200,200);
      f.setVisible(true);
  }
}

感谢。

2 个答案:

答案 0 :(得分:1)

坐标系中心(0,0)绘制在(w / 2,h / 2)处。缺少的部分是比例,换句话说:有多少像素在x轴和y轴上形成一个单位。

通常,您将单位值乘以比例因子(如10,如果您想要每单位10个像素),并从左边界或下边界添加轴的偏移量。恼人的部分是屏幕坐标上的(0,0)是左上角,高度从上到下计数(反转的y轴)。这使它变得更复杂:

 xOnScreenPos =  (xUnit * xScale) + xScaleOffset;
 yOnScreenPos = -(yUnit * yScale) + yScaleOffset;

答案 1 :(得分:1)

import java.awt.*;
import javax.swing.*;  
public class Graph extends JPanel {
   private static final int UNIT = 20;
   protected void paintComponent(Graphics g) {
     int YP1,YP2;
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;

      int h = getHeight();
         int w = getWidth();
         // Draw axeX.
         g2.draw(new Line2D.Double(0, h/2, w, h/2)); //to make axisX in the middle
         // Draw axeY.
         g2.draw(new Line2D.Double(w/2,h,w/2,0));//to make axisY in the middle of the panel

                  //line between P1(0,1) and P2(1,2) to draw function x+1
    Point2D P1 = new Point2D.Double(w/2,(h/2)+ UNIT);
    Point2D P2 = new Point2D.Double((w/2)+ UNIT,(h/2)+ 2*UNIT);  //considering 20 = 1 unit in your syste,
     g2.draw(new Line2D.Double(P1,P2));
}
public static void main(String[] args) {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.add(new Graphe());
      f.setSize(400,400);
      f.setLocation(200,200);
      f.setVisible(true);
  }
}   

试用此代码阅读评论以获得解决方案