我有兩個擴展JPanel的類:MapPanel和CityPanel。我試圖將一個CityPanel繪製到MapPanel中,但沒有出現。我不明白爲什麼如果我以相同的方式添加一個JButton它將被完美顯示。 下面的代碼:將JPanel繪製到JPanel中
public class PanelMap extends JPanel {
public PanelMap() {
CityPanel city = new CityPanel();
city.setVisible(true);
this.add(city);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
public class CityPanel extends JPanel {
private BufferedImage image;
public CityPanel() {
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Test", 0, 0); }
}
編輯:
我--cityMap中的代碼。它顯示字符串,但沒有圖像。
public CityPanel(String filePath, int red, int green, int blue) {
this.image = colorImage(filePath, red, green, blue);
this.setSize(100, 100);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 50, 50, null);
g.drawString("sdjkfpod", 50, 50);
}
'@Override protected void paintComponent(Graphics g){ super.paintComponent(g); '這個代碼完全沒有意義。它所實現的一切就是確保該方法完全執行如果重寫的方法丟失的情況。 –
由於'CityPanel'不提示大小,'PanelMap'具有默認的'FlowLayout',因此城市面板將爲0x0像素,並且不會顯示。添加一個紅色的'LineBorder',以證明它自己更普遍:爲了更好的幫助更快,發佈一個[MCVE]或[簡短,獨立,正確的例子](http://www.sscce.org/)。 –
給你的內部面板的大小... –