I try to add some components to an JPanel. paintComponent()
is called, but the components won't display. revalidate()
didn't work.
The structure looks like the following:
public class AbstractView extends JPanel implements ViewInterface {
}
public class GraphView extends AbstractView {
public void doSomeStuff(){
this.add(new ElementView());
this.revalidate();
}
}
public class ElementView extends AbstractView {
@Override
public void paintComponent(Graphics g) {
// this method is called but has no effect
super.paintComponent(g);
g.fillRect(0,0,100,100);
this.repaint();
}
}
I think that's the relevant code. Methods like getPreferredSize()
and even getX()
,getY()
,getWidth()
,getHeight()
are implemented and seem to work like expected. I searched Google for hours, but nothing seems to help. Am i searching the bug at the right location?
edit:
Here is some more of the Code:
1:
public class AbstractView extends JPanel implements ViewInterface {
@Override
public void update() {}
@Override
public boolean containsPoint(Point p) {
return false;
}
@Override
public ApplicationView topContainer() {
return null;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(this.getBounds().getSize());
}
@Override Rectangle getBounds(){
return Rectangle(0,0,0,0);
}
@Override
public int getX() {
return this.getBounds().x;
}
@Override
public int getY() {
return this.getBounds().y;
}
@Override
public int getWidth() {
return this.getBounds().width;
}
@Override
public int getHeight() {
return this.getBounds().height;
}
}
2:
class BodyView extends AbstractView {
Body body;
BodyView(Body b, AbstractView c){
this.body = b;
this.setLayout(null);
}
private int radius(){
return (int) body.radius();
}
@Override
public void paintComponent(Graphics g) {
// called but without effect
super.paintComponent(g);
g.setColor(this.color);
int x = (int) body.position.at(0);
int y = (int) body.position.at(1);
int radius = radius();
g.fillOval(x-radius, y-radius, 2*radius, 2*radius);
}
@Override
public Rectangle getBounds(){
int radius = this.radius();
return new Rectangle(getX() - radius - 2, getY() - radius - 2, 2*radius + 2, 2*radius + 2);
}
@Override
public int getX() {
return (int) body.position.at(0);
}
@Override
public int getY() {
return (int) body.position.at(1);
}
}
3:
class SpaceView extends AbstractView {
Space space;
Set<BodyView> bodyViews;
SpaceView(Space s, AbstractView c){
this.space = s;
this.initializeBodyViews();
this.setLayout(null);
}
private void initializeBodyViews(){
bodyViews = new HashSet<BodyView>();
for(Body body : space.bodies){
BodyView view = new BodyView(body, this);
// new components are added here
addBodyView(view);
}
}
public void addBodyView(BodyView view){
bodyViews.add(view);
this.add(view);
}
}
If this isn't enough to determine the problem i would like to refer to this Github.