如何将图像绘制到JPanel或JFrame? [英] How do I draw an image to a JPanel or JFrame?

查看:162
本文介绍了如何将图像绘制到JPanel或JFrame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将图像绘制到JPanel或JFrame,我已经阅读了oracle的教程,但我似乎无法做到正确。我需要在一组特定坐标上显示图像 BeachRoad.png 。以下是我到目前为止。

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

在Main()中,

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

提前致谢!

推荐答案

试试这个:

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


}

这篇关于如何将图像绘制到JPanel或JFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆