【发布时间】:2016-07-02 10:31:39
【问题描述】:
我有两个扩展 JPanel 的类:MapPanel 和 CityPanel。我正在尝试将 CityPanel 绘制到 MapPanel 中,但没有出现任何内容。我不明白为什么如果我以同样的方式添加 JButton 它将完美显示。 代码如下:
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来证明给自己看 更一般地说:为了尽快获得更好的帮助,请发布minimal reproducible example 或Short, Self Contained, Correct Example。 -
给你的内面板尺寸...
-
嗨@AndrewThompson 你觉得我的回答有什么问题吗?
-
嗨@Jean-BaptisteYunès 你能看看我的回答并告诉我我使用的任何不正确的信息吗?