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

时间:2015-08-05 11:22:18

标签: java swing paint jcomponent

我只是不明白这一点。我想将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的样子。 注意我正在调用LayoutManager时未使用super(null);

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);    
    }
}

1 个答案:

答案 0 :(得分:1)

看起来问题是坐标空间

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

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

getBounds()返回组件的父容器上的矩形。所以当你只能打电话给g.fillRect(0, 0, bounds.width, bounds.height);