所以,我有一个 JLayeredPane(实际上是 JLayeredPane 的子类)。上面有一个 JPanel。我想向 Jpanel 添加 BufferedImage。
public class BigMap extends JLayeredPane implements MouseListener
JPanel mapPanel;
BufferedImage theMap;
public BigMap (BufferedImage m){
theMap = m;
mapPanel = new JPanel();
add(mapPanel, 0);
mapPanel.setBounds(0, 0, 640, 640);
//other unimportant stuff
}
@Overrride
public void paintComponent (Graphics g){
super.paintComponent(g);
Graphics2D gmap = (Graphics2D) mapPanel.getGraphics();
gmap.drawImage(theMap, null, 0, 0);
//some other stuff which is working just fine
}
问题是 BufferedImage 未显示。 JPanel 肯定存在,因为我可以设置其背景颜色并在需要时查看它。我意识到 JLayeredPane 没有布局管理器,并且必须设置 JPanel 的边界,但这对于 JPanel 本身来说应该不是问题,当然吗?鉴于 BufferedImage 缺乏直接控制其大小的方法,我不知道如果是的话我将如何克服这个问题。
感谢任何帮助。
最佳答案
这里的问题是您重写了分层 Pane 的 paintComponent()
方法,而不是 JPanel
。 JPanel
稍后将自行绘制,作为分层 Pane 的子 Pane 之一,这将清除您绘制的内容。
一般来说,paintComponent()
方法应该绘制到为其提供的Graphics
中,而不是绘制到其他组件的图形中。
关于java - 将 BufferedImage 添加到 JLayerPane 上的 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15644686/