(转)如何在JPanel面板中设置背景图片 | 您所在的位置:网站首页 › java面板设置背景图片 › (转)如何在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 JPanel23 {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 else48 x+=icon.getIconWidth();49 }50 }51 }52 53 }54 55 56
SCAU_QUE: 由于遇见一些人出现利用JLabel标签来给面板添加背景,噢,不可以说是背景,仅仅是 添加了一张图片而已。 |
CopyRight 2018-2019 实验室设备网 版权所有 |