I'm trying to develop an editor which you can insert text and draw shapes on. To do this, I'm using a JPanel as the main panel, and listening to mouse actions I add new JPanels into it. I draw the shapes on the small panels using getGraphics(). But the main panel somehow prevents the small panels from displaying their contents. When repaint is called we can see a glimpse of the ovals and lines inside the panels, but then they disappear. If I use JEditorPane as the main canvas, then they are displayed correctly. Why does JPanel do this?
public class SectionPage extends JPanel {
private int drawMode = 0;
ArrayList<JComponent> pageComponents;
ArrayList<ReportElement> reportElements;
JTextArea tempTextArea;
JPanel tempPanel;
JComponent tempComponent;
BasicStroke stroke;
float[] dashes;
public SectionPage() {
dashes = new float[]{10.0f, 10.0f};
pageComponents = new ArrayList<JComponent>();
reportElements = new ArrayList<ReportElement>();
setBackground(Color.white);
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
int x1, y1;
int x2, y2;
this.removeAll();
for (int i = 0; i < reportElements.size(); i++) {
tempComponent = new JPanel();
x1 = reportElements.get(i).getX1();
y1 = reportElements.get(i).getY1();
x2 = reportElements.get(i).getX2();
y2 = reportElements.get(i).getY2();
if (x1 > x2 && y1 > y2) {
tempComponent.setLocation(x2, y2);
tempComponent.setSize(x1 - x2, y1 - y2);
} else if (x1 < x2 && y1 > y2) {
tempComponent.setLocation(x1, y2);
tempComponent.setSize(x2 - x1, y1 - y2);
} else if (x1 < x2 && y1 < y2) {
tempComponent.setLocation(x1, y1);
tempComponent.setSize(x2 - x1, y2 - y1);
} else if (x1 > x2 && y1 < y2) {
tempComponent.setLocation(x2, y1);
tempComponent.setSize(x1 - x2, y2 - y1);
}
//tempComponent.setBackground(Color.red);
this.add(tempComponent);
reportElements.get(i).display((Graphics2D) tempComponent.getGraphics());
}
}