Java this小技巧

当我们在写程序使,经常遇到相同的变量名无法区分,于是就使用:

   this.a = a;

 

来区分,而当我们在使用嵌套类时,this就发生了混淆,我们不能得到外包类的this,所以就是用如下方式:

 

 CLASSNAME.this

 

例子程序:

/**
 *LookAndFeel.java
 * Created on 9:01:54 AM Feb 27, 2009
 *@author Quasar063501
 *@version 0.1
 *
 */
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class LookAndFeel extends JFrame {
 private JPanel buttonPanel = null;
 
 public void launchFrame() {
  this.setSize(200,300);
  buttonPanel = new JPanel();
  UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();
  //new for
  for(UIManager.LookAndFeelInfo info : infos) {
   makeButton(info.getName(),info.getClassName());
  }
  
  this.add(buttonPanel);
  this.setVisible(true);
 }

 private void makeButton(String bName, final String lookName) {
  JButton b = new JButton(bName);
  buttonPanel.add(b);
  
  b.addActionListener(new ActionListener(){

   public void actionPerformed(ActionEvent e) {
    try {
     UIManager.setLookAndFeel(lookName);
    } catch (ClassNotFoundException e1) {
     e1.printStackTrace();
    } catch (InstantiationException e1) {
     e1.printStackTrace();
    } catch (IllegalAccessException e1) {
     e1.printStackTrace();
    } catch (UnsupportedLookAndFeelException e1) {
     e1.printStackTrace();
    }
    SwingUtilities.updateComponentTreeUI(LookAndFeel.this);
   }
  
  });
 }
 
 public static void main(String[] args) {
  new LookAndFeel().launchFrame();
 }
}

你可能感兴趣的:(Java this小技巧)