2010-09-29 67 views
1

即時通訊設法制作一個繪製函數圖形的簡單應用程序(現在很簡單,例如:x + 2) 但我有問題根據屏幕座標對點進行數學座標。 我希望它在我的圖形中畫出一條從P1(0,1)到P2(1,2)的直線。java二維圖紙

這裏是我的代碼:

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); 
    } 
} 

感謝。

+0

你能否詳細說明您的問題。 – 2010-09-29 09:22:51

回答

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); 
    } 
} 

試用此代碼閱讀評論,從而更好的解決方案

1

座標系統的中心(0,0)繪製爲(w/2,h/2)。缺少的部分是比例尺,換句話說:x軸和y軸上有多少個像素組成一個單位。

所以通常你用你的單位值乘以比例係數(如10,如果你想每個單位10個像素),並添加從左邊界或下邊界軸的偏移量。煩人的部分是屏幕上的(0,0)座標是左上角,高度是從上到下計數(顛倒y軸)。這使得它有點複雜:

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