@Override
public void paintComponent(Graphics gs) {
Graphics2D g = (Graphics2D) gs
super.paintComponent(g)
//画背景图片
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource(imgPath))
g.drawImage(image, 0, 0,width,height, this)
}
一个完整的代码:
package testimport java.awt.Graphics
import java.awt.Image
import java.net.URL
import javax.swing.ImageIcon
import javax.swing.JFrame
import javax.swing.JPanel
public class JFrameBackground {
private JFrame frame = new JFrame("带背景图片的JFrame")
private JPanel imagePanel
private ImageIcon backgroundimg
public JFrameBackground() {
imagePanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g)
URL location = this.getClass().getResource("grapes.gif")
backgroundimg = new ImageIcon(location)
Image img = backgroundimg.getImage()
g.drawImage(img, 0, 0, backgroundimg.getIconWidth(),
backgroundimg.getIconHeight(),
backgroundimg.getImageObserver())
frame.setSize(backgroundimg.getIconWidth(),
backgroundimg.getIconHeight())
}
}
frame.add(imagePanel)
frame.setVisible(true)
frame.pack()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
}
public static void main(String[] args) {
new JFrameBackground()
}
}
这是运行的一个截图:
参考网址:
http://www.linuxidc.com/Linux/2011-08/41689.htm 两种设置背景的方法
http://blog.csdn.net/one_and_only4711/article/details/6594770 动态改变背景大小
JPanel p=new JPanel()JLabel l=new JLabel()
Icon icon=new ImageIcon("D:\\rk01.jpg")//在此直接创建对象
l.setIcon(icon)
l.setBounds(0, 0, icon.getIconWidth(),icon.getIconHeight())
p.add(l,new Integer(Integer.MIN_VALUE))
这样可以给panel加一个背景图
要在JPanel中显示图片可以将一JLabel控件加入其中,在JLabel中添加图片,如:
JLabel lb = new JLabel(new ImageIcon(".\\xxx\\xx.jpg"))
jPanel1.add(lb)
应该可以,不知是否会答非所问?
package baidu.zhidao
import java.awt.BorderLayout
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import javax.swing.ImageIcon
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JPanel
/**
* 如何在JPanel中显示图片
* @author jink2005
*
*/
public class ImagePane extends JPanel
{
JLabel jl = null
ImageIcon img = null
/**
* @param args
*/
public ImagePane()
{
img = new ImageIcon("E:\\eclipse\\workspace\\Study\\baidu\\zhidao\\horse.jpg")
jl = new JLabel(img)
this.setLayout(new BorderLayout())
this.add(jl, BorderLayout.CENTER)
}
public static void main(String[] args)
{
JFrame test = new JFrame("Image Pane")
test.getContentPane().add(new ImagePane())
test.pack()
test.setVisible(true)
test.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0)
}
})
}
}
欢迎访问我的学习日志http://jink2005.blog.sohu.com/和我一起交流。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)