gpt4 book ai didi

Java:将 JComponents 添加到具有静态大小和定位的 JPanel

转载 作者:行者123 更新时间:2023-11-29 06:14:22 24 4
gpt4 key购买 nike

我有一个程序可以在不使用第三方库的情况下在 Java 应用程序中读取和绘制 SVG 文件。我已经到了可以通过将形状绘制到图形对象上来复制文件的地步,但是我想通过将监听器应用于每个对象来使每个元素(Rect/Circle/Line 等)可选择。

为此,我的印象是我需要创建一个扩展 JComponent 的类,在组件内绘制对象并为要显示的每个元素添加一个监听器。所以我会有一组容器组件(如果你可以这样调用它们的话),并附加了监听器,每个都对应于文件中的一个特定元素。

然后我需要将这些组件绘制到 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();
}
}

最佳答案

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

附录:关于 JLayeredPane , 另见 tutorial ,这相关example ,还有这个 variation .

关于Java:将 JComponents 添加到具有静态大小和定位的 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5667843/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com