我創建了自定義的swing組件。我可以看到它(繪製方法繪製的網格),但添加的按鈕(由println驗證)未顯示。我究竟做錯了什麼?組件未在自定義JPanel/JComponent中顯示
背景信息:我正在嘗試構建一個可見對象樹,如Flash/AS3顯示列表。
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);
}
}
}
順便說一句,super.paintComponent()沒有必要,因爲你的代碼完全用fillRect()方法填充背景。同樣在JComponent的情況下,paintComponent()方法沒有默認的繪製代碼。但是,通常建議調用paintComponent()方法,除非您有特殊原因不這樣做。 – camickr 2010-06-03 17:07:39