【发布时间】: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