« Struts2 文件上传简介 | Main | 用NetBeans进行PHP实例(许愿树... »
http://developers.sun.com.cn/blog/functionalca/date/20090501 星期五 2009年05月01日

如何给JPanel加上背景图片

如何给JPanel加上背景图片
作者:曹祺
Blog: http://blogs.sun.com/greysh
Web: http://www.greysh.com
Email: Qi.Cao@Sun.com
本文链接:
http://developers.sun.com.cn/blog/functionalca/entry/%E5%A6%82%E4%BD%95%E7%BB%99jpanel%E5%8A%A0%E4%B8%8A%E8%83%8C%E6%99%AF%E5%9B%BE%E7%89%87
源代码下载:
http://developers.sun.com.cn/blog/functionalca/resource/Greysh/FCA_Greysh_Panel.zip
难度:入门

1.简介
2.代码实现

 1.简介
标准的JPanel由于不能添加背景图片,所以需要一个Image Panel,但是Panel的构造函数不能添加图像,具体的实习就是先写一个JPanel的子类,然后去创建此类的时候,添加Image,然后将Panel给重绘

2.代码实现
子类
package com.greysh;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;

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

public class JImagePanel extends JPanel {
 private static final long serialVersionUID = 1L;
 BorderLayout borderLayout = new BorderLayout();
 private ImageIcon image = null;

 public JImagePanel(ImageIcon image) throws Exception {
  this.image = image;
  JImagePanelInit();
 }

 private void JImagePanelInit() throws Exception {
  this.setLayout(borderLayout);
 }

 protected void paintComponent(Graphics g) {
  setOpaque(true);
  super.paintComponent(g);
  Dimension d = getSize();
  for (int x = 0; x < d.width; x += image.getIconWidth())
   for (int y = 0; y < d.height; y += image.getIconHeight())
    g.drawImage(image.getImage(), x, y, null, null);
 }
}

测试效果类
package com.greysh;

import java.awt.BorderLayout;
import java.awt.Dimension;

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

public class JTestFrame extends JFrame {

 private static final long serialVersionUID = 1L;

 public static void main(String[] args) throws Exception {
  JTestFrame jtestframe = new JTestFrame();
  JPanel jpanel = (JPanel) jtestframe.getContentPane();
  jpanel.setLayout(new BorderLayout());
  ImageIcon image = new ImageIcon(JTestFrame.class.getResource("logo.jpg"));
  JImagePanel jimagepanel = new JImagePanel(image);
  jpanel.add(jimagepanel);
  jtestframe.setSize(new Dimension(400, 300));
  jtestframe.setTitle("JImagePanel");
  jtestframe.setDefaultCloseOperation(EXIT_ON_CLOSE);
  jtestframe.setVisible(true);
 }
}
然后运行用
java com.greysh.JTestFrame



发表于 Sun Functional 校园大使 [JavaEE] ( 五月 01, 2009 12:55 上午 ) Permalink | 评论[0]
评论:

发表一条评论:
  • HTML语法: 禁用