//FocusEvent1.java
//焦点事件,前一版本中txt1不能自动换行,加入了自动换行。
//2099-11-15 V0.2
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FocusEvent1 extends JFrame
{
FocusEvent1(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("txt2:focus gained in button1 or txt1");
}
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);
cp.add(button1);
cp.add(button2);
txt1.addFocusListener(keyTry);
txt1.setLineWrap(true); //txt1自动换行
cp.add(sh);
cp.add(txt2);
}
public static void main(String[] args){
FocusEvent1 focusEvent=new FocusEvent1("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);
}
}