【问题标题】:Drawing an image on Jpanel [closed]在 Jpanel 上绘制图像 [关闭]
【发布时间】:2014-05-19 02:01:31
【问题描述】:

我试图设置 JPanel 女巫的背景图像位于 JFrame 内。我尝试了很多事情,例如在其中放置一个带有 IconImage 的 JLable,并且我尝试了覆盖 paintComponent 类。

for(int i = 0; i<4; i++){
    JPanel panel = new JPanel();

    panel.setPreferredSize(new Dimension(450,125));

    ImageIcon icon = new ImageIcon(image);

    panel.repaint();
    left.add(panel);
    left.revalidate();
    repaint();
    }
}

public void paintComponent(Graphics g){
    super.paintComponents(g);
        g.drawImage(backgroundImage, 0, 0, this);
}

【问题讨论】:

  • 实际的runnable example that demonstrates your problem 将涉及更少的猜测工作和更好的响应
  • 如果您的代码不起作用,并且您遇到了问题,那么请显示该代码。描述问题。显示错误。说"I've searched for tutorials" 并没有告诉我们任何用处。请改进此问题,以便有机会回答。
  • “但 super.paintComponent(g) 部分似乎给出了错误。” 那么您要扩展的类不会直接或以其他方式从 JComponent 扩展.考虑发布一个实际的runnable example that demonstrates your problem,这将涉及更少的猜测和更好的响应
  • 编辑的问题和代码。

标签: java image swing jpanel paint


【解决方案1】:

您的问题在细节上仍然乏善可陈,您还没有发布实际的runnable example that demonstrates your problem,但是您的帖子:

所以我试图将图像作为 JLabel 的背景。我试过使用:

public void paintComponent(Graphics g){
    super.paintComponent(g);
}

但是 super.paintComponent(g) 部分似乎报错了。

建议不要将这段代码放在扩展 JPanel 或 JComponent 的类中。

建议:

  • 将该方法放在扩展 JPanel 的类中。
  • 在您的方法上方放置一个@Override 注释,以确保您实际上正确地覆盖了该方法。
  • 将代码放入该方法中以获取 Graphics 对象 g 来绘制图像。我会在超级电话之后拨打g.drawImage(...)
  • 请注意,paintComponent(Graphics g) 方法应声明为 protected 而不是 public
  • 在本网站和教程中重新阅读此类代码的示例。由于您遗漏了很多信息,因此您对信息的审核没有很仔细。
  • 如果这些建议仍然没有帮助,那么再次创建并发布您的runnable example that demonstrates your problem

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 1970-01-01
    相关资源
    最近更新 更多