JPanel带有背景图片 [英] JPanel with a background image
本文介绍了JPanel带有背景图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
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);
}
}
以及以下内容:
public GUIVenDetails() throws MalformedURLException, IOException{
mapPanel = new ImagePanel("http://www.netstate.com/states/symb/gamebirds/images/wild_turkey.jpg");
mapPanel.setPreferredSize(new Dimension(200,200));
mapPanel.setMinimumSize(mapPanel.getPreferredSize());
mapPanel.setMaximumSize(mapPanel.getPreferredSize());
add(mapPanel);
}
public static void main(String[] args) throws MalformedURLException, IOException, XPathExpressionException, SAXException, ParserConfigurationException {
GUIVenDetails gui = new GUIVenDetails();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension windowSize = gui.getSize();
int windowX = Math.max(0, (screenSize.width - windowSize.width ) / 2);
int windowY = Math.max(0, (screenSize.height - windowSize.height) / 2);
JFrame f=new JFrame();
f.setSize(new Dimension(400,800));
f.setLocation(windowX, windowY);
f.add(gui);
f.setVisible(true);
}
运行代码时,我什么都看不到,除了白色……为什么?
When I run the code, I don't see anything but white... Why is this?
推荐答案
那不是您从互联网上读取文件的方式.尝试类似的东西:
That is not how you read a file from the internet. Try something like:
String imagePath = "http://duke.kenai.com/misc/Bullfight.jpg";
Image image = null;
try
{
URL url = new URL(imagePath);
image = ImageIO.read(url);
}
catch (IOException e)
{
System.out.println(e);
}
或者您仍然可以使用
new ImageIcon(new URL(...));
但是字符串不能仅因为它以"http"开头就成为URL.
But a String does not become a URL just because it starts with "http".
这篇关于JPanel带有背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文