Java:使用静态大小调整和定位将JComponent添加到JPanel

|| 我有一个程序,可以在不使用第三方库的情况下在Java应用程序中读取和绘制SVG文件。我已经到了可以通过在图形对象上绘制形状来复制文件的地步,但是我想通过将侦听器应用于每个对象来使每个元素(Rect / Circle / Line等)可选。 为此,我的印象是需要创建一个扩展JComponent的Class,在该组件内绘制Object并为要显示的每个元素向其添加一个侦听器。因此,我将拥有一组带有附加的侦听器的容器组件(如果可以调用它们的话),每个侦听器对应于文件中的特定元素。 然后,我需要将这些组件绘制到JPanel或合适的Container上,但是这样做,我将需要使用空布局并手动设置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();
    }
}
    
已邀请:
如本例所示,“ 1”是传统方法。在
GraphPanel
中可以看到使用
paintComponent()
的另一种方法。 附录:关于ѭ1,另请参阅本教程,此相关示例和此变体。     
OOdium 您所描述的内容听起来确实合理,据我所知,2D API中没有对事件的本地支持。如果视觉元素之间存在重叠,则必须小心。解决该问题的另一种方法是在画布顶部(Z顺序或玻璃窗格)上有一个ѭ5,该ѭ负责确定单击了哪个项目,然后触发适当的事件。如果存在重叠的视觉实体,则可能有必要。以下是来自Sun的分层文档:http://download.oracle.com/javase/tutorial/uiswing/components/rootpane.html 我不是图形人员,但是我希望程序员能够经常执行自己想做的事情,因此能为您的要求提供标准的解决方案。您可能想尝试使用Java内置的2D游戏进行谷歌搜索,看看是否可以从中学到的东西中学习。 问候, 圭多     

要回复问题请先登录注册