我有一個程序在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();
}
}
另請參見[爲SVG應用程序賦予Java應用程序](http://java.sun.com/developer/technicalArticles/GUI/svg/)。 – trashgod 2011-04-16 16:55:44