package com.aa;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener; import javax.swing.*;
//事件监听
import javax.swing.*;
class West7 extends JFrame implements ActionListener,KeyListener{//这里的键盘监听也是的,必须实现接口里的方法
//因为实现ActionListener接口,
JButton jb1,jb2,jb3;
JPanel jp;
JTextField jt;
JTextArea ta; public West7(){ ta=new JTextArea(12,30);
jt=new JTextField(20);
jt.addActionListener(this);
jb1=new JButton("OK");
jb2=new JButton("Exit");
jp=new JPanel();
jb1.addActionListener(this);//只要实现了AcitonListener接口,参数this就可以正常了
jp.add(ta);
jp.add(jt);
jp.add(jb1);
jb2.addKeyListener(this);//键盘监听
jp.add(jb2);
this.add(jp);
this.setVisible(true);
this.setDefaultCloseOperation(3);
this.setBounds(100, 200, 500, 300);//就是把对象jb2注册给事件监听者new ActinoListener
jb2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){//这是一个匿名的内部类,用来实现对动作事件的处理 } } { @Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub }
}) } public void send(){
String s=jt.getText().trim(); }
public void actionPerformed(ActionEvent e){
//重写方法
//好奇怪,竟然没有报错 String s=e.getActionCommand();//利用getActionCommand获取按钮名称
if(s.equals("OK")){
Component frame;
JOptionPane.showMessageDialog(frame, "32");
}else if(s.equals("Exit")){ JOptionPane.showMessageDialog(frame, "哈哈");
}else { JOptionPane.showMessageDialog(frame, "我呢");
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub }
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER){
send(); //System.out.println("你好");
} }
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub }
public static void main(String[] args) {
West7 w=new West7();
JFrame frame = new JFrame("默默");
frame.getContentPane().add(comp) }
}