Java – how to draw images to JPanel or JFrame?
•
Java
I have read the Oracle tutorial on how to draw images to JPanel or JFrame, but I can't seem to do it correctly I need to display the image "beachroad. PNG" on a specific set of coordinates This is me so far
public class Level1 extends JFrame implements ActionListener { static JLayeredPane EverythingButPlayer; static Level1 l1; public Level1() { EverythingButPlayer = new JLayeredPane(); BufferedImage img = null; try { img = ImageIO.read(new File("BeachRoad.png")); } catch (IOException e) { } Graphics g = img.getGraphics(); g.drawImage(img,EverythingButPlayer); this.add(EverythingButPlayer); }
In main(),
l1 = new Level1(); l1.setTitle("poop"); l1.setSize(1920,1080); l1.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); l1.setVisible(true);
Thank you in advance!
Solution
Try this:
package com.sand@R_736_2419@; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.WindowConstants; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class SwingSand@R_736_2419@ { public static void main(String[] args) throws IOException { JFrame frame = buildFrame(); final BufferedImage image = ImageIO.read(new File("C:\\Projects\\MavenSand@R_736_2419@\\src\\main\\resources\\img.jpg")); JPanel pane = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image,null); } }; frame.add(pane); } private static JFrame buildFrame() { JFrame frame = new JFrame(); frame.setDefaultCloSEOperation(WindowConstants.EXIT_ON_CLOSE); frame.setSize(200,200); frame.setVisible(true); return frame; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码