Components don't show in custom JPanel/JComponent

Posted by Bart van Heukelom on Stack Overflow See other posts from Stack Overflow or by Bart van Heukelom
Published on 2010-06-03T15:11:25Z Indexed on 2010/06/03 15:14 UTC
Read the original article Hit count: 275

Filed under:
|

I've created a custom swing component. I can see it (the grid from the paint method is drawn), but the buttons that are added (verified by println) aren't shown. What am I doing wrong?

Background information: I'm trying to build a tree of visible objects like the Flash/AS3 display list.

public class MapPanel extends JComponent { // or extends JPanel, same effect

    private static final long serialVersionUID = 4844990579260312742L;

    public MapPanel(ShapeMap map) {
        setBackground(Color.LIGHT_GRAY);
        setPreferredSize(new Dimension(1000,1000));
        setLayout(null);
        for (Layer l : map.getLayers()) {
//          LayerView layerView = new LayerView(l);
//          add(layerView);
            System.out.println(l);
            JButton test = new JButton(l.getName());
            add(test);
            validate();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {

        // necessary?
        super.paintComponent(g);

        // background
        g.setColor(getBackground());
        g.fillRect(0, 0, getWidth(), getHeight());

        // grid
        g.setColor(Color.GRAY);         
        for (double x = 0; x < getWidth(); x += 10) {
            g.drawLine((int)x, 0, (int)x, getHeight());
        }
        for (double y = 0; y < getHeight(); y += 10) {
            g.drawLine(0, (int)y, getWidth(), (int)y);
        }

    }

}

© Stack Overflow or respective owner

Related posts about java

Related posts about swing