0

我尝试将一些组件添加到 JPanel。paintComponent()被调用,但组件不会显示。revalidate()没用。

结构如下所示:

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

我认为这是相关的代码。getPreferredSize()甚至getX(), getY(), getWidth(),之类的方法getHeight()已实现并且似乎按预期工作。我在谷歌上搜索了几个小时,但似乎没有任何帮助。我是否在正确的位置搜索错误?

编辑:

这是更多的代码:

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

如果这还不足以确定问题,我想参考这个 Github

4

0 回答 0