java – 如何将图像绘制到JPanel或JFrame?

前端之家收集整理的这篇文章主要介绍了java – 如何将图像绘制到JPanel或JFrame?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我如何将图像绘制到JPanel或JFrame,我已经阅读了oracle的教程,但我似乎无法正确的.我需要将图像“BeachRoad.png”显示在一组特定的坐标上.这是我到目前为止.
  1. public class Level1 extends JFrame implements ActionListener {
  2.  
  3. static JLayeredPane EverythingButPlayer;
  4. static Level1 l1;
  5.  
  6. public Level1() {
  7. EverythingButPlayer = new JLayeredPane();
  8.  
  9. BufferedImage img = null;
  10. try {
  11. img = ImageIO.read(new File("BeachRoad.png"));
  12. } catch (IOException e) {
  13. }
  14. Graphics g = img.getGraphics();
  15. g.drawImage(img,EverythingButPlayer);
  16.  
  17.  
  18. this.add(EverythingButPlayer);
  19. }

在Main()中,

  1. l1 = new Level1();
  2. l1.setTitle("poop");
  3. l1.setSize(1920,1080);
  4. l1.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
  5. l1.setVisible(true);

提前致谢!

解决方法

尝试这个:
  1. package com.sandBox;
  2.  
  3. import javax.imageio.ImageIO;
  4. import javax.swing.JFrame;
  5. import javax.swing.JPanel;
  6. import javax.swing.WindowConstants;
  7. import java.awt.Graphics;
  8. import java.awt.image.BufferedImage;
  9. import java.io.File;
  10. import java.io.IOException;
  11.  
  12. public class SwingSandBox {
  13.  
  14. public static void main(String[] args) throws IOException {
  15. JFrame frame = buildFrame();
  16.  
  17. final BufferedImage image = ImageIO.read(new File("C:\\Projects\\MavenSandBox\\src\\main\\resources\\img.jpg"));
  18.  
  19. JPanel pane = new JPanel() {
  20. @Override
  21. protected void paintComponent(Graphics g) {
  22. super.paintComponent(g);
  23. g.drawImage(image,null);
  24. }
  25. };
  26.  
  27.  
  28. frame.add(pane);
  29. }
  30.  
  31.  
  32. private static JFrame buildFrame() {
  33. JFrame frame = new JFrame();
  34. frame.setDefaultCloSEOperation(WindowConstants.EXIT_ON_CLOSE);
  35. frame.setSize(200,200);
  36. frame.setVisible(true);
  37. return frame;
  38. }
  39.  
  40.  
  41. }

猜你在找的Java相关文章