2011-04-14 56 views
1

我有一個程序在Java應用程序中讀取和繪製SVG文件,而不使用第三方庫。我已經到了可以通過將圖形繪製到圖形對象上來複制文件的地步,但是我想通過將偵聽器應用於每個對象來使每個元素(Rect/Circle/Line等)可選。Java:添加JComponents到具有靜態大小和定位的JPanel

爲此,我需要創建一個擴展JComponent的類,在組件中繪製對象,併爲每個要顯示的元素添加一個偵聽器。所以我會有一組容器組件(如果可以調用它們的話),並附帶一個偵聽器,每個對應於文件中的特定元素。

然後我需要將這些組件繪製到JPanel或合適的容器上,但是爲此我需要使用null佈局並手動設置JPanel/Container中每個組件的位置和大小。

因此,總而言之,儘管這正是我想要做的,但我想知道是否有更加標準化的方法來將偵聽器添加到圖形對象中,但我並不知道?

這裏是有問題的代碼,我期待通過使用上述方法來擴展的樣本,我已經簡化它了很多,所以我希望它仍然是有意義的

public class View extends JComponent implements SVGViewport { 

    // Model of the SVG document 
    private SVGDocument document; 

    /** Paint method */ 
    @Override 
    protected void paintComponent(Graphics g) { 
     paint2D((Graphics2D) g); 
    } 

    /** Paints the entire view */ 
    private void paint2D(Graphics2D g) { 
     // Paint Document properties 
     .... 

     // Paint document Elements 
     for (SVGElement elem : document) { 
      paintElement(g, elem); 
     } 
    } 

    /** Paints a single element on the graphics context */ 
    public void paintElement(Graphics2D g, SVGElement elem) { 

     //Get a drawable shape object for this element 
     Shape shape = elem.createShape(); 

     //Set Fill, stroke, etc attributes for this shape 
     .... 
     // Fill the interior of the shape 
     .... 
     // Stroke the outline of the shape 
     .... 
     g.draw(shape); 
    } 

    /** Gets the document currently being displayed by the view. */ 
    public SVGDocument getDocument() { 
     return document; 
    } 

    /** set and re-paint the document */ 
    public void setDocument(SVGDocument document) { 
     this.document = document; 
     repaint(); 
    } 
} 
+0

另請參見[爲SVG應用程序賦予Java應用程序](http://java.sun.com/developer/technicalArticles/GUI/svg/)。 – trashgod 2011-04-16 16:55:44

回答

2

JLayeredPane是傳統方法,因爲在這個example看出。使用paintComponent()的替代方法可以在GraphPanel中看到。

附錄:關於JLayeredPane,另請參閱此tutorial,此相關example和此variation

+0

我知道必須有更好的方式JLayeredPane正是我所追求的!謝謝 – 2011-04-14 22:14:22

+0

優秀。我在上面添加了一些相關鏈接。 – trashgod 2011-04-14 22:52:35

1

OOdium,

您所描述的內容當然聽起來很合理,據我所知,2D API中沒有對事件的本機支持。如果視覺元素之間有重疊,則必須小心。另一種解決方法是在畫布頂部(Z-order或Glass Pane)上設置一個JComponent,負責確定哪個項目被點擊,然後觸發相應的事件。如果有重疊的視覺實體,這可能是必要的。這裏是來自Sun的分層文檔:http://download.oracle.com/javase/tutorial/uiswing/components/rootpane.html

雖然我不是一個圖形傢伙,但我期望有一個標準的解決方案來滿足您的要求,因爲程序員想要做你想做的事情的頻率。您可能想嘗試使用Java編寫的2D遊戲搜索,看看您是否可以從他們的工作中學習。

問候,

+0

+1遊戲和一般的模擬遊戲是豐富的思想源泉。 – trashgod 2011-04-16 16:52:34