FocusEvent

本文介绍了一个Java Swing应用程序示例,展示了如何通过焦点事件(FocusEvent)区分不同组件获得焦点的情况,并实现文本区域自动换行的功能。

 //FocusEvent2.java
//焦点事件,前一版本中txt1不能自动换行,加入了自动换行。
//前一版本中焦点获得不知道是txt1产生的还是button1产生的,此次实现了区分。
//2099-11-15 V0.3

 

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;

 

public class FocusEvent2 extends JFrame
{
 FocusEvent2(String title){
  super(title);
 }
 JButton button1=new JButton("button1");
 JButton button2=new JButton("button2");
 JTextArea txt1=new JTextArea(null,5,20);
 
 JTextField txt2=new JTextField(20);
 
 JScrollPane sh=new JScrollPane(txt1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
  JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

 class KeyTry implements FocusListener
 {
  public void focusGained(FocusEvent e){     //焦点获得
   txt1.setText("txt1:paramString()="+e.paramString());
   txt2.setText("the focus is on "+((JComponent)e.getSource()).getName());
                   //利用获得名字来区分。e.getSource()方法返回Ob
                   // ject型值,getName()为JComponent方法,因此需转换一下。
  }
  public void focusLost(FocusEvent e){      //焦点失去
   txt1.setText("txt1:paramString()="+e.paramString());
   txt2.setText("txt2:focus losed in button1 or txt1");
  }
 }

 KeyTry keyTry=new KeyTry();
 public void init(){
  Container cp=getContentPane();
  cp.setLayout(new FlowLayout());
  button1.addFocusListener(keyTry);
  button1.setName("buuton1");
  txt1.setName("txt1");
  cp.add(button1);
  cp.add(button2);
  txt1.addFocusListener(keyTry);
  txt1.setLineWrap(true);            //txt1自动换行
  txt1.setWrapStyleWord(true);         //换行不断字
  cp.add(sh);
  cp.add(txt2);
 }
 
 public static void main(String[] args){
  FocusEvent2 focusEvent=new FocusEvent2("Focus Event");
  focusEvent.init();
  focusEvent.setSize(240,180);
  focusEvent.setVisible(true);
  focusEvent.addWindowListener(new WindowClose()); 
 } 
}

class WindowClose extends WindowAdapter
{
 public void windowClosing(WindowEvent e){
  System.exit(0);
 }
}

 

在 init 方法中,增加了为构件起名的语句,使用的是 setName 方法,这个方法可在
Component的范围内调用。同时,要注意构件的名字Name和构件的文本 Text 是不同的。
在 Listener 中,调用构件的名字用 getName 方法,这个方法也是 Component 类才有。程
序的难点在((JComponent)e.getSource()).getName(), 它的意思是调用e.getSource()得到发生事
件的对象,因为 e.getSource()返回 Object 类型,所以加上 JComponent 把类型转换过来(当
然也可以转换成 Component),最后再调用getName()方法得到构件的名字。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值