java 如何为一个窗体设置背景图片

来源:互联网 发布:linq to sql distinct 编辑:程序博客网 时间:2024/05/21 21:47

要为一个窗体添加背景图片,必须知道绘制JComponent组件的过程。Swing轻量组件的绘制是组件和组件UI代表合作的结果。 


代码  设置窗体背景图片:

 

[java] view plaincopy
  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. import javax.swing.*;  
  4.    
  5. public class GraExp extends JFrame  
  6. {   
  7. CInstead c1=new CInstead();  
  8. Container c;  
  9. JLabel lbl1=new JLabel("姓名:" );  
  10. JLabel lbl2=new JLabel("密码:" );  
  11. JTextField tf1=new JTextField(10),  
  12. tf2=new JTextField(10);  
  13.    
  14. public GraExp()  
  15. {   
  16. setContentPane(c1);  
  17. c=getContentPane();  
  18. c.setLayout(new FlowLayout(FlowLayout.LEFT));  
  19. c.add(lbl1);  
  20. c.add(tf1);  
  21. c.add(lbl2);  
  22. c.add(tf2);  
  23.    
  24. setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);  
  25. setSize(new Dimension(400,300));  
  26. show();  
  27. }   
  28. public static void main(String[] args)  
  29. {   
  30. GraExp ge=new GraExp();  
  31. }   
  32. class CInstead extends JPanel  
  33. {   
  34. ImageIcon icon;  
  35. Image img;  
  36. public CInstead()  
  37. {   
  38. icon=new ImageIcon(GraExp.class.getResource("333.png" ));  
  39. img=icon.getImage();  
  40. }   
  41. public void paintComponent(Graphics g)  
  42. {   
  43. super.paintComponent(g);  
  44. g.drawImage(img,0,0,null );  
  45. }   
  46. }   
  47. }   

 


界面运行图如下: 

程序分析: 
JComponent.paint先绘制组件,然后绘制组件的边框,再绘制组件的子组件。调用的顺序确保组件、边框和子组件都是可视的。如果组件有一个 UI代表,则JComponent.paintComponent调用该代表的Update方法,该方法为不透明组件擦除背景,然后绘制组件。 
CInstead是一个不透明的组件,如果重载paint方法,其背景图是无法被擦除的,因此,即使更新了组件的所有包含组件,在界面上是看不到的。所以必须重载paintComponent方法,在绘制子组件前先擦除背景。 
对双缓存组件,paint方法负责把组件绘制到屏外缓存中,然后把屏外缓存拷贝到组件的屏上代表中,正因为如此,
我们不建议为Swing组件重载paint,如果需要重新定义如何绘制组件,那么就重载paintComponent()。 

 

0 0
原创粉丝点击