【问题标题】:Adding a BufferedImage to a JPanel on JLayerPane将 BufferedImage 添加到 JLayerPane 上的 JPanel
【发布时间】:2013-03-26 18:26:55
【问题描述】:

所以,我有一个 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 肯定存在,因为我可以设置它的 backgroundColour 并根据需要查看它。我意识到 JLayeredPane 没有布局管理器,并且必须为 JPanel 设置边界,但这对 JPanel 本身来说应该不是问题,对吧?鉴于 BufferedImage 缺乏直接控制其大小的方法,我不知道如果是这样,我将如何克服它。

任何帮助表示赞赏。

【问题讨论】:

  • mapPanel.getGraphics() 为什么在已经拥有方法参数的Graphics g 的情况下尝试获取另一个Graphics 对象?无论如何,您检索到的 Graphics 可能是无效的。作为一般规则,不要在组件上使用getGraphics
  • 这仅仅是因为我最终将在 JLayeredPane 上拥有其他 JPanel 并打开他们自己的图像。这是一种保持整洁的尝试——每个面板的图形负责自己的内容。不好的做法?
  • 小组对自己的内容负责。不好的做法 不,但这是在代码调用paint/paintComponent 之前为您完成的。您应该永远不需要照顾图形,Swing 会在适当的时候提供适当的图形。只需不要在任何组件上调用getGraphics,您应该就可以了。

标签: java swing bufferedimage paintcomponent jlayeredpane


【解决方案1】:

这里的问题是您覆盖了分层窗格的paintComponent() 方法,而不是JPanelJPanel 稍后将自己绘制,作为分层窗格的子项之一,这将清除您绘制的内容。

一般来说,paintComponent() 方法应该绘制到给它的 Graphics,而不是绘制到其他组件的图形中。

【讨论】:

  • 啊,我没有意识到这一点。回到我猜的教程。非常感谢你,接受并投票。
  • 现在可以根据您的回答进行更改,完美运行。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多