我有一个程序可以在不使用第三方库的情况下在 java 应用程序中读取和绘制 SVG 文件。我已经到了可以通过将形状绘制到图形对象上来复制文件的地步,但是我想通过将侦听器应用于每个对象来使每个元素(矩形/圆形/线条等)都可以选择。
为此,我的印象是我需要创建一个扩展 JComponent 的类,在组件中绘制对象,并为要显示的每个元素添加一个侦听器。所以我会有一组容器组件(如果你可以调用它们的话)并附加了监听器,每个都对应于文件中的一个特定元素。
然后我需要将这些组件绘制到 JPanel 或合适的 Container 上,但是为此我需要使用 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();
}
}