在Jpanel上绘制图像

时间:2014-05-19 02:01:32

标签: java image swing jpanel paint

我试图设置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);
}

1 个答案:

答案 0 :(得分:2)

您的问题仍然在细节方面仍然存在,您仍然没有发布实际的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