//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()方法得到构件的名字。