2016-11-11 95 views
1

我想用Line2D類創建線,但是當我跑我的課,我收到這樣的:創建Line2D對象

Linia:[email protected]

這裏是我的代碼:

class linia { 

    public java.awt.geom.Line2D.Double getLine() { 
     return line; 
    } 

    public void setLine(java.awt.geom.Line2D.Double line) { 
     this.line = line; 
    } 
    private java.awt.geom.Line2D.Double line; 

} 

public class Lines { 

    public static java.awt.geom.Line2D.Double create(double x1, double y1, double x2, double y2) { 
     java.awt.geom.Line2D.Double tmpL = new java.awt.geom.Line2D.Double(); 
     tmpL.x1 = x1; 
     tmpL.y1 = y1; 
     tmpL.x2 = x2; 
     tmpL.y2 = y2; 
     return tmpL; 

    } 

    public static void main(String[] args) { 
     linia line = new linia(); 
     line.setLine(create(Double.valueOf(1), Double.valueOf(1), Double.valueOf(2), Double.valueOf(2))); 
     System.out.println("Line: " + line.getLine()); 
    } 

} 
+3

你是怎麼想到這個打印出來? – tkausl

回答

0

我看到你在linia類沒有默認構造函數。另一種選擇是根據參數和任何初始化要求添加自定義構造函數。

Java在任何類定義中都需要構造函數。

class Linia 
{ 
    public Linia() { 
     // here you add any default implementation required 
    } 

    public java.awt.geom.Line2D.Double getLine() { 
     return line; 
    } 
    public void setLine(java.awt.geom.Line2D.Double line) 
    { 
     this.line = line; 
    } 
} 

注:在Java中的命名約定更喜歡Java類將大寫字母開頭,因此它是一個很好的做法給你打電話類Linia,而不是linia

0

可以使用getBounds()方法打印線的座標

public static void main(String[] args) { 
    linia line = new linia(); 
    line.setLine(create(Double.valueOf(1), Double.valueOf(1), Double.valueOf(2), Double.valueOf(2))); 
    System.out.println("Line: " + line.getLine().getBounds()); 
} 

預期輸出:

Line: java.awt.Rectangle[x=1,y=1,width=1,height=1]