Swing页面属性的设置顺序

这是一个细节问题,但细节问题关乎一个软件的设计成败,我想这个例子可以充分说明这个问题。 

问题是这样产生的,我给一个JPanel设置了一幅背景图片,结果我发现绘制图像的protected void paintComponent(Graphics g)方法,总是调用两次,于是着手调查原因,因为连续调用联系protected void paintComponent(Graphics g)方法,并将占用大量的时间,让Swing页面加载明显减慢。当您的protected void paintComponent(Graphics g)方面里有复杂和大量的画图程序时,加载变慢更加明显。 

最后我发现protected void paintComponent(Graphics g)之所以连续调用两次,竟然因为以下两行代码: 
Java代码    收藏代码
  1. setSize(610440);  
  2. setVisible(true);  


如果我把这两行代码颠倒顺序,程序就只调用protected void paintComponent(Graphics g)一次: 
Java代码    收藏代码
  1. setVisible(true);     
  2. setSize(610440);  


另外这两行代码的顺行竟然还会影响您页面的显示效果,您也许觉得玄乎,请看画面: 

当我们用setVisible(true);setSize(610, 440);顺序执行程序时,显示页面: 

//pic

protected void paintComponent(Graphics g)方法调用一次,页面也显示正常。 

当我们用setSize(610, 440);setVisible(true);顺序执行程序时,显示页面: 

//pic


protected void paintComponent(Graphics g)方法调用两次,页面也显示不正常,请大家注意红框位置。 

好了现在大家知道了吧,我们在Swing设置显示顺行的时候,要把设置窗体尺寸大小方法setSize放在窗体可见方法setVisible后面。如下: 

Java代码    收藏代码
  1. private MainFrame01() {  
  2.         setTitle("ZakiSoft Demo");  
  3.         con = getContentPane();  
  4.         ZPanel zp = new ZPanel();  
  5.         zp.setBackground(new javax.swing.ImageIcon(getClass()  
  6.                 .getResource("/com/zakisoft/frame02/demo.jpg")));  
  7.   
  8.         con.add(zp);  
  9.   
  10.         setVisible(true);      
  11.         setSize(610440);  
  12.   
  13.         setResizable(false);  
  14.         setLocationRelativeTo(getOwner());  
  15.         setDefaultCloseOperation(EXIT_ON_CLOSE);  
  16.   
  17.     }  


之所以会产生以上的现象,我查看了源码问题可能出在Component类的repaintParentIfNeeded方法。 
Java代码    收藏代码
  1. private void repaintParentIfNeeded(int oldX, int oldY, int oldWidth,  
  2.                                       int oldHeight)   
  3.    {  
  4.        if (parent != null && peer instanceof LightweightPeer && isShowing()) {  
  5.            // Have the parent redraw the area this component occupied.  
  6.            parent.repaint(oldX, oldY, oldWidth, oldHeight);                      
  7.            // Have the parent redraw the area this component *now* occupies.  
  8.            repaint();  
  9.        }  
  10.    }  

如果我们提前设置了setVisible,可以减少一次repaint(); 

附件是一个完整的例子,运行代码可以给一个JPanel设置背景图片。 

文章地址: http://javapub.iteye.com/blog/763970

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值