如何在Eclipse Helios中设置JFrame或JPanel背景图像 [英] How to set JFrame or JPanel Background Image in Eclipse Helios

查看:264
本文介绍了如何在Eclipse Helios中设置JFrame或JPanel背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经google了,找到了代码:

I've googled it and found the code:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ImageTest {

  public static void main(String[] args) {
    ImagePanel panel = new ImagePanel(new ImageIcon("background.png").getImage());

    JFrame frame = new JFrame();
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
  }
}

class ImagePanel extends JPanel {

  private Image img;

  public ImagePanel(String img) {
    this(new ImageIcon(img).getImage());
  }

  public ImagePanel(Image img) {
    this.img = img;
    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);
    setSize(size);
    setLayout(null);
  }

  public void paintComponent(Graphics g) {
    g.drawImage(img, 0, 0, null);
  }
}

当我创建ImageTest.java文件,并将background.png放在同一个文件夹中。

This worked for me when I create the ImageTest.java file, and put the background.png in the same folder.

但是当我在Eclipse IDE(默认包)中粘贴相同的代码以及图像时,不将图像设置为背景。实际上它没有找到图像,这是原因。

But when I paste the same code in Eclipse IDE (in default package) along with the image, then it doesn't set the image as background. Actually it doesn't find the images and this is the reason.

我已经尝试将它们保持在相同的包中; 即使这样,它也找不到图像,所以没有输出。

I've tried keeping them both in same package pack; Even then it doesn't find the image, so no output.

我试图打开工作区>项目文件夹> war> WEB-INF > classes
然后从cmd编译程序。仍然没有显示。

I've tried to open the workspace > project folder > war > WEB-INF > classes Then compiled the program from cmd. Still it doesn't show.

我不知道是什么问题。任何知道任何解决方案的人最受欢迎。

I don't know what the problem is. Anyone knowing any solution is most welcomed.

感谢提前。

将背景直接设置到框架上也是欢迎...

Setting background directly onto the frame is also welcomed...

我已经完成了所有这些使用代码,但是当这将工作,那么我将转移到Windows生成器的GUI。那么你的帮助也会在窗口生成器中工作?

I've done all this using code, but when this will be working then I'll be shifting to windows builder for GUI. So will the help from you will work in window builder also?

推荐答案

..new ImageIcon("background.png")..  

这是一个愚蠢(但常见的)加载方式不提供反馈的图像 1

This is a stupid (but common) way to load an image that provides no feed-back1.

你很可能会发现 background.png 不再是一个文件,而是现在是Jar的一部分。在这种情况下,访问它的方式是使用从 Class.getResource()获取的 URL 。 >

You will most likely find that the background.png is no longer a file but now part of a Jar. In that case, the way to access it is using an URL obtained from Class.getResource().


  1. 加载图片的聪明方式是使用 ImageIO ,这有助于&如果图像无法加载,则提供丰富的例外。

这篇关于如何在Eclipse Helios中设置JFrame或JPanel背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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