我有两个扩展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/)。 –
给你的内部面板的大小... –