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