初学java之事件响应(结合接口来设置在同一个界面上!)

时间:2024-04-29 03:44:53
 package wahaha;

 public class test_1 {
public static void main( String args[] )
{
WindowActionEvent win = new WindowActionEvent();
PoliceListen police = new PoliceListen(); //创建监视器
win.setMyCommandListener(police);
win.setBounds(100, 100, 460, 360);
win.setTitle("处理ACtionEvent事件");
}
}

main_class

 package wahaha;

 import javax.swing.*;
import java.awt.*; public class WindowActionEvent extends JFrame
{ JTextField inputText ;
JTextArea testshow ;
JButton button ;
MyCommandListener listenner ; public WindowActionEvent()
{
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} void init()
{
setLayout(new FlowLayout());
inputText =new JTextField(10);
button =new JButton("确定");
testshow = new JTextArea(9,30);
add(inputText);
add(button);
add(new JScrollPane(testshow));
} void setMyCommandListener(MyCommandListener listener)
{
this.listenner = listener ;
listener.setJTextArea(testshow);
listener.setJTextField(inputText);
//inputText是事件源,listener是监视器
button.addActionListener(listener) ;
//button是事件源 ,listener是监视器
}
}

demo

  package wahaha;

 //设置一个接口 implements/interface/extends

 import javax.swing.* ;
import java.awt.event.* ; public interface MyCommandListener extends ActionListener //子接口多给出了2个方法
{
public void setJTextField(JTextField text);
public void setJTextArea(JTextArea area);
}
   package wahaha;

   import javax.swing.*;
import java.awt.event.*; public class PoliceListen implements MyCommandListener
{
JTextField textInput ;
JTextArea textshow ; public void setJTextField( JTextField text )
{
textInput = text ;
} public void setJTextArea(JTextArea area)
{
textshow = area;
} public void actionPerformed( ActionEvent e)
{
String str=textInput.getText();
textshow.append(str+"的长度:"+str.length()+"\n");
}
}

初学java之事件响应(结合接口来设置在同一个界面上!)