将JPanel绘制成JPanel

Draw JPanel into JPanel

我有两个 类 扩展 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);
    }

能否请您替换 PanelMap.java 的以下构造函数:

public PanelMap() {
  CityPanel city = new CityPanel();
  city.setVisible(true);
  this.add(city);
}

通过以下构造函数:

public PanelMap() {
    String filePath = "C:\...\city2.png";
    CityPanel city = new CityPanel(filePath, 0, 255, 255);       
    this.setLayout(new BorderLayout());
    this.add(city, BorderLayout.CENTER);        
}

看到结果了吗?

已对您的代码进行了以下更改:

  • 语句 city.setVisible(true); 已删除,因为它不是 根本不需要。
  • 声明 this.add(city); 确实是将 CityPanel 添加到 PanelMapCityPanel 占用很小 space 看起来像 非常小的矩形。这就是 BorderLayout 的原因 用过。

以下 PanelMapDemo.java 添加 PanelMapJFrame 并创建一个可执行示例。

public class PanelMapDemo extends javax.swing.JFrame {
private static final long serialVersionUID = 1L;

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            PanelMapDemo demoFrame = new PanelMapDemo("PanelMapDemo");
            demoFrame.setVisible(true);
        }
    });
}

public PanelMapDemo(String title) {
    super(title);
    setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
    add(new PanelMap());
    setSize(new java.awt.Dimension(400, 200));
    setLocationRelativeTo(null);
 }
}

在我的系统上,原始图片是:

您的 MapPanel 将图片更改为:

希望,这有帮助。