问题
I just don't get this. I want to add Highlight extends JComponent
objects to a PdfPage extends JPanel
but the Highlight
components are simple not painted. I can see that their paint()
and paintComponent()
methods are getting called in correct order but they do not show. The only thing that fixes my problem is to add:
for(Component component : this.getComponents()) {
component.paint(g);
}
into the PdfPanel.paint()
method but this is not how I want to do that. I want PdfPage extends JPanel
to render any JComponent
I'm adding but not override paint()
if possible.
This is how I add Highlight
components to PdfPage
panels:
for (DatasheetError datasheetError : datasheetErrorList) {
int pageNumber = datasheetError.getPageNumber();
Highlight highlight = createErrorHighlight(datasheetError);
PdfPage pdfPage = pdfPages[pageNumber];
pdfPage.add(highlight);
}
This is how PdfPage
looks like. Note that I am not using a LayoutManager
as I am calling 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());
}
}
In Highlight.java you can see that I call 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:
Looks like problem is coordinate space
protected void paintComponent(Graphics g) {
...
Rectangle bounds = this.getBounds();
g.setColor(this.fillColor);
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
...
}
The getBounds() returns the component's rectanle on parent container. So when you can call just g.fillRect(0, 0, bounds.width, bounds.height);
来源:https://stackoverflow.com/questions/31831099/painting-multiple-jcomponent-on-jpanel-not-working