【问题标题】:Add an image to a canvas [duplicate]将图像添加到画布 [重复]
【发布时间】:2020-04-30 08:07:16
【问题描述】:

我知道这里有关于此的堆栈溢出问题,但我没有在课堂上扩展画布。有没有其他方法可以在背景上绘制图像?

//setting up a JFrame with other stuff
Canvas c = new Canvas();
Image img;
try {
    img = ImageIO.read(new URL("https://bitterli.us/namelogo.png").openStream());
    img = img.getScaledInstance(700, 145, 0);
} catch (IOException e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
}
c.setBackground(Color.black);
JPanel p = new JPanel();
c.setBounds(100, 500, 1050, 500);
p.setLayout(new BorderLayout());
p.add(c, BorderLayout.CENTER);
p.setBounds(100, 50, 1050, 600);
frame.add(p, BorderLayout.NORTH);

【问题讨论】:

  • 您需要扩展 Canvas(根据其他问题)并在其绘制方法中绘制。要么添加 JLabel 并将图像显示为标签内的 ImageIcon 。你为什么要使用 AWT GUI 库,因为它已经过时了 20 多年?
  • 另外,setBounds 不是你的朋友

标签: java swing graphics awt


【解决方案1】:

不要使用画布,只需使用 JPanel 并覆盖 paintComponent()

public void paintComponent(Graphics g) {
  super.paintComponent(g);
  g.drawImage(img, 0, 0, null);
}

【讨论】:

猜你喜欢
  • 2015-05-19
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 2011-10-20
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多