How do I draw an image to a JPanel or JFrame?

断了今生、忘了曾经 提交于 2019-11-26 11:25:48

问题


How do I draw an Image to a JPanel or JFrame, I have already read oracle\'s tutorial on this but I can\'t seem to get it right. I need the image \"BeachRoad.png\" to be displayed on a specific set of coordinates. Here is what I have 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,0, 0, EverythingButPlayer);


    this.add(EverythingButPlayer);
}

And in the Main(),

        l1 = new Level1();
    l1.setTitle(\"poop\");
    l1.setSize(1920, 1080);
    l1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    l1.setVisible(true);

Thanks in advance!


回答1:


Try this:

package com.sandbox;

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 SwingSandbox {

    public static void main(String[] args) throws IOException {
        JFrame frame = buildFrame();

        final BufferedImage image = ImageIO.read(new File("C:\\Projects\\MavenSandbox\\src\\main\\resources\\img.jpg"));

        JPanel pane = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(image, 0, 0, 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;
    }


}



回答2:


There are a lot of methods, but I always override the paint(Graphics g) of a JComponent and use g.drawImage(...)

edit: I was making a sample, but tieTYT did it perfectly, look at his answer :)



来源:https://stackoverflow.com/questions/17865465/how-do-i-draw-an-image-to-a-jpanel-or-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!