1

我有一个程序可以在不使用第三方库的情况下在 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();
    }
}
4

2 回答 2

2

AJLayeredPane是传统方法,如本例所示paintComponent()可以在 中看到使用的替代方法GraphPanel

附录:关于JLayeredPane,另请参阅本教程、此相关示例和此变体

于 2011-04-14T18:48:15.490 回答
1

钠,

您所描述的内容当然听起来很合理,而且据我所知,2D API 中没有对事件的原生支持。如果视觉元素之间存在重叠,则必须小心。另一种解决方法是JComponent在画布顶部(Z 顺序或玻璃窗格)负责确定单击了哪个项目,然后触发适当的事件。如果存在重叠的视觉实体,这可能是必要的。以下是 Sun 的分层文档:http: //download.oracle.com/javase/tutorial/uiswing/components/rootpane.html

虽然我不是图形专家,但我希望有一个标准的解决方案来满足你的要求,因为程序员想要做你想做的事情的频率。您可能想尝试用谷歌搜索用 Java 构建的 2D 游戏,看看您是否可以从他们所做的事情中学习。

问候,

圭多

于 2011-04-14T18:41:46.303 回答