サードパーティのライブラリを使用せずに、Java アプリケーションで SVG ファイルを読み込んで描画するプログラムがあります。グラフィックス オブジェクトに形状を描画することでファイルを複製できるようになりましたが、各オブジェクトにリスナーを適用して各要素 (Rect/Circle/Line など) を選択可能にしたいと考えています。
そのためには、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();
}
}