import java.awt.Graphics
import java.awt.Toolkit
import java.awt.Image
import java.awt.Panel
public class ImgPanel extends Panel {
Image img
public ImgPanel(Image img){
this.img = img
}
@Override
public void paint(Graphics g) {
super.paint(g)
g.drawImage(img, 20,20,40,40, this)//其中第二到第五个参数分别为x,y,width,height
}
}
然后在别的地方添加这个ImgPanel控件就好了,比如:
Panel p = new ImgPanel(Toolkit.getDefaultToolkit().createImage("A:\\projects\\gui\\lightbulb.jpg")))
p.setBounds(0, 0, 80, 80)
this.add(p)
你用了32个panel当然卡了,每个panel创建都需要时间,而且很耗费资源,如果你要想做一个象棋盘最好的方式就是直接把棋子绘制到窗体上,在窗体的Paint事件里,给你举个例子private void Form1_Paint(object sender, PaintEventArgs e)
{
Bitmap bit = new Bitmap("E:\\ABC.jpg")//从文件创建一个位图
e.Graphics.DrawImage(bit, new Point(10, 10))//把位图绘制在窗体的(10,10)这个坐标上
bit.Dispose()
}
你可以用循环将指定的棋子绘制到指定的位置
//重写JPanel的这个方法就可以了@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 动态改变背景大小
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)