Java this小技巧

本文介绍了一个Java Swing程序,该程序允许用户通过按钮点击切换不同的用户界面外观和感觉(LookAndFeel)。程序利用了UIManager类来获取已安装的LookAndFeel,并为每种LookAndFeel创建一个按钮,点击后会更改整个应用程序的外观。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

   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();
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值