(转)如何在JPanel面板中设置背景图片

 
  
1 import java.awt. * ;
2 import javax.swing. * ;
3
4 public class Demo extends JFrame
5 {
6 public Demo()
7 {
8 super ( " Title " );
9 NewPanel p = new NewPanel();
10 this .getContentPane().add(p); // 将面板添加到JFrame上
11 this .setSize( 596 , 298 ); // 初始窗口的大小
12 this .setLocationRelativeTo( null ); // 设置窗口居中
13 this .setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14 this .setVisible( true );
15 }
16
17 public static void main(String[] args)
18 {
19 new Demo();
20 }
21
22 class NewPanel extends JPanel
23 {
24 public NewPanel()
25 {
26
27 }
28
29 public void paintComponent(Graphics g)
30 {
31 int x = 0 ,y = 0 ;
32 java.net.URL imgURL = getClass().getResource( " test.jpg " );
33
34 // test.jpg是测试图片,与Demo.java放在同一目录下
35 ImageIcon icon = new ImageIcon(imgURL);
36 g.drawImage(icon.getImage(),x,y,getSize().width,getSize().height, this );
37 while ( true )
38 {
39 g.drawImage(icon.getImage(),x,y, this );
40 if (x > getSize().width && y > getSize().height) break ;
41 // 这段代码是为了保证在窗口大于图片时,图片仍能覆盖整个窗口
42 if (x > getSize().width)
43 {
44 x = 0 ;
45 y += icon.getIconHeight();
46 }
47 else
48 x += icon.getIconWidth();
49 }
50 }
51 }
52
53 }
54
55
56

 

 

 SCAU_QUE: 由于遇见一些人出现利用JLabel标签来给面板添加背景,噢,不可以说是背景,仅仅是 添加了一张图片而已。

转载于:https://www.cnblogs.com/SCAU_que/articles/1752677.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值