Java 怎么给JFrame添加背景图片

Java 怎么给JFrame添加背景图片,第1张

//分少点,就给你个JFrame的例子吧。呵呵,善用搜索引擎。

import java.awt.event.*

import javax.swing.*

import java.awt.*

public class BackgroundImage extends JFrame

{

JScrollPane scrollPane

ImageIcon icon

Image image

public BackgroundImage()

{

icon = new ImageIcon("bgpanel.jpg")

JPanel panel = new JPanel()

{

protected void paintComponent(Graphics g)

{

// Dispaly image at at full size

g.drawImage(icon.getImage(), 0, 0, null)

// Scale image to size of component

//Dimension d = getSize()

//g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null)

// Fix the image position in the scroll pane

//Point p = scrollPane.getViewport().getViewPosition()

//g.drawImage(icon.getImage(), p.x, p.y, null)

super.paintComponent(g)

}

}

panel.setOpaque( false )

panel.setPreferredSize( new Dimension(400, 400) )

scrollPane = new JScrollPane( panel )

getContentPane().add( scrollPane )

JButton button = new JButton( "Hello" )

panel.add( button )

}

public static void main(String [] args)

{

BackgroundImage frame = new BackgroundImage()

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

frame.setSize(300, 300)

frame.setLocationRelativeTo( null )

frame.setVisible(true)

}

}

JFrame j = new JFrame()

JButton b = new JButton() // // 实例化按钮对象,并且设置按钮上显示图片

b.setIcon(new ImageIcon("f://1.jpg")) ////1.jpg是要添加的图片

j.add(b)

j.setSize(300, 200)

j.setVisible(true)

代码及说明参考上面代码及注释

public class GraphicFrame extends JFrame

{

Image image

int x

int y

public GraphicFrame(Image i,int x,int y)//在这里将image对象,还有起始的坐标传进去

{

this.image = i

this.x = x

this.y = y

}

public void paintComponent(Graphics g)

{

super.paintComponent(g)

drawImage(image, x, y, null)

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11567560.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存