Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }


}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...