在 JPanel 上绘制多个 JComponent 不起作用

Painting multiple JComponent on JPanel not working

我就是不明白。我想将 Highlight extends JComponent 个对象添加到 PdfPage extends JPanel,但 Highlight 组件很简单,没有绘制。我可以看到他们的 paint()paintComponent() 方法以正确的顺序被调用,但它们没有显示。解决我的问题的唯一方法是添加:

for(Component component : this.getComponents()) {           
    component.paint(g);         
}

进入 PdfPanel.paint() 方法,但这不是我想要的方式。我希望 PdfPage extends JPanel 呈现我正在添加的任何 JComponent,但如果可能的话不要覆盖 paint()

这就是我将 Highlight 组件添加到 PdfPage 面板的方式:

for (DatasheetError datasheetError : datasheetErrorList) {

    int pageNumber = datasheetError.getPageNumber();
    Highlight highlight = createErrorHighlight(datasheetError);

    PdfPage pdfPage = pdfPages[pageNumber];     
    pdfPage.add(highlight);
}

这就是 PdfPage 的样子。 请注意 我在调用 super(null);:

时没有使用 LayoutManager
public class PdfPage extends JPanel  {
    private static final long serialVersionUID = 7756137054877582063L;

    final Image pageImage;

    public PdfPage(Image pageImage) {
        // No need for a 'LayoutManager'
        super(null);

        this.pageImage = pageImage;     
        Rectangle bounds = new Rectangle(0, 0, pageImage.getWidth(null), pageImage.getHeight(null));
        this.setBounds(bounds);
        this.setLayout(null);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        paintPdfPage(g);
    }

    private void paintPdfPage(Graphics g) {
        // For now transparent background to see if `Highlight` gets painted
        g.setColor(new Color(1.0f, 1.0f, 1.0f, 0.0f));
        g.fillRect(0, 0, getWidth(), getHeight());
    }

}

Highlight.java中你可以看到我调用了this.setBounds(bounds);

public class Highlight extends JComponent {
    private static final long serialVersionUID = -1010170342883487727L;

    private Color borderColor = new Color(0, 0, 0, 0);

    private Color fillColor;

    public Highlight(Rectangle bounds, Color fillColor) {
        this.fillColor = fillColor; 
        this.setBounds(bounds);
    }

    @Override
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);

        Rectangle bounds = this.getBounds();

        g.setColor(this.fillColor);
        g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);

        g.setColor(this.borderColor);
        g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height);    
    }
}

看来问题是坐标 space

protected void paintComponent(Graphics g) {
...
        Rectangle bounds = this.getBounds();

        g.setColor(this.fillColor);
        g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
...
    }

getBounds() returns 组件的矩形 在父容器上 。所以当你可以只调用 g.fillRect(0, 0, bounds.width, bounds.height);